This repository has been archived by the owner on May 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathloader.js
62 lines (54 loc) · 1.75 KB
/
loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/** Copyright (c) 2018 Uber Technologies, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {Locale, Locales} from 'locale';
import fs from 'fs';
import path from 'path';
import {memoize} from 'fusion-core';
import type {Context} from 'fusion-core';
import type {TranslationsObjectType} from './types.js';
export type I18nLoaderType = {
from: (
ctx: Context
) => {locale: string | Locale, translations: TranslationsObjectType},
};
export type LocaleResolverType = (ctx: Context) => string;
export type LoaderFactoryType = (
resolveLocales?: LocaleResolverType
) => I18nLoaderType;
const defaultResolveLocales: LocaleResolverType = ctx =>
ctx.headers['accept-language'];
const loader: LoaderFactoryType = (resolveLocales = defaultResolveLocales) => {
const readDir = root => {
try {
return fs.readdirSync(root);
} catch (e) {
return [];
}
};
const root = './translations';
const locales = readDir(root)
.filter(p => p.match(/json$/))
.map(p => p.replace(/\.json$/, ''));
const data = locales.reduce((memo, locale) => {
const parsedLocale = new Locale(locale);
memo[parsedLocale.normalized] = JSON.parse(
fs.readFileSync(path.join(root, locale + '.json'), 'utf8')
);
return memo;
}, {});
const supportedLocales = new Locales(locales);
return {
from: memoize(ctx => {
const expectedLocales = new Locales(resolveLocales(ctx));
const locale = expectedLocales.best(supportedLocales);
const translations: TranslationsObjectType = data[locale.normalized];
return {translations, locale};
}),
};
};
export default (((__NODE__ ? loader : null): any): typeof loader);