-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
223 lines (188 loc) · 6.86 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
'use strict';
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
// Utils
const notEmpty = val => val !== undefined && val !== null;
const safeObjVal = (obj, keys) => {
return keys.reduce((nestedObject, key) => {
return nestedObject && nestedObject[key];
}, obj);
};
const isString = (val) => {
return typeof val === 'string';
};
const isArray = (val) => {
return Array.isArray(val);
};
const isObject = (val) => {
return (val instanceof Object) && !isArray(val);
};
const continueWhileEmpty = values => values.reduce((result, val) => {
return (notEmpty(result) ? result : (notEmpty(val) ? val : null));
}, null);
const isLanguage = (localeOrLanguage) => (localeOrLanguage && (localeOrLanguage.split('_').length === 1));
const localeToLanguage = (locale) => (locale.split('_').shift());
const languageToLocale = (language, locales) => locales.find(loc => (localeToLanguage(loc) === language));
const compareLocales = (localeOrLanguage, locale) => {
if (isLanguage(localeOrLanguage)) {
return localeOrLanguage === localeToLanguage(locale);
}
return localeOrLanguage === locale;
};
module.exports = (options) => {
let translations; // TODO: make this immutable
if (!isString(options.translationFolder)) {
throw('Missing translationFolder');
}
if (!isArray(options.locales)) { // TODO: guess those from files
throw('Missing locales');
}
options = Object.assign({
debug: false,
defaultLocale: options.locales[0],
queryParameters: ['lang'],
cookieName: 'i18n',
}, options);
const warnResult = function(result, warningString) {
const args = Array.prototype.slice.call(arguments);
if (options.debug) {
console.warn.apply(null, [warningString, result].concat(args.slice(2)));
}
return result;
};
const doReplaceData = (string, replaceData) => {
if (!isString(string)) return string;
return string.replace(/\$\{(.+?)\}/g, (fullMatch, subMatch) => {
return replaceData[subMatch] || warnResult(subMatch, 'Missing interpolation:');
});
};
const load = () => {
return new Promise((resolveAll, rejectAll) => {
fs.readdir(options.translationFolder, (err, files) => {
return Promise.all(files.map(file => {
const fileName = file.replace(new RegExp(path.extname(file) + '$'), '');
return new Promise((resolve, reject) => {
fs.readFile(`${options.translationFolder}/${file}`, 'utf8', (err, content) => {
resolve({[fileName]: yaml.safeLoad(content)});
});
});
})).then((objects) => {
translations = objects.reduce((result, object) => {
return Object.assign(result, object);
}, {});
resolveAll(translations);
});
});
}).catch(err => rejectAll('Error loading content:', err));
};
const strictTranslate = (translationRoot, path, replaceData, locale) => {
if (notEmpty(translationRoot)) {
if (path.length === 0) {
return doReplaceData(continueWhileEmpty([
translationRoot[locale],
translationRoot[localeToLanguage(locale)],
translationRoot
]), replaceData);
} else {
const nextPath = path[0];
const nextRoot = continueWhileEmpty([
safeObjVal(translationRoot, [nextPath]),
safeObjVal(translationRoot, [locale, nextPath]),
safeObjVal(translationRoot, [localeToLanguage(locale), nextPath])
]);
return strictTranslate(nextRoot, path.slice(1), replaceData, locale);
}
} else {
const lastPath = path[path.length - 1];
if (lastPath) {
return warnResult(lastPath, 'Wrong path to translation', path);
}
}
};
const looseTranslate = (arg1, arg2, arg3, arg4, selectedLocale) => {
let translationRoot, path, replaceData;
let partitionArgs = [arg1, arg2, arg3, arg4].reduce((result, arg) => {
let isLocale = isString(arg) && options.locales.indexOf(arg) > -1;
return {
locale: isLocale ? arg : result.locale,
otherArgs: result.otherArgs.concat(isLocale ? [] : [arg])
};
}, {
locale: selectedLocale,
otherArgs: []
});
let args = partitionArgs.otherArgs;
let locale = partitionArgs.locale;
if (isString(args[0])) { // no translationRoot provided
translationRoot = translations;
path = args.shift();
} else {
translationRoot = args.shift();
path = args.shift();
}
replaceData = args.shift() || {};
// console.log('from', arg1, arg2, arg3, arg4, selectedLocale);
// console.log('get', translationRoot, path, replaceData, locale);
return strictTranslate(translationRoot, path.split('.'), replaceData, locale);
};
const guessFromHeaders = req => {
const languageHeader = safeObjVal(req, ['headers', 'accept-language']);
if (languageHeader) {
return languageHeader.split(',').map(language => {
const preferenceParts = language.trim().split(';q=');
return {
locale: preferenceParts[0],
score: preferenceParts[1] || 1
};
}).sort((a, b) => {
return b.score - a.score;
}).map(el => el.locale);
}
return [];
};
const findBestLocale = (queriedValues) => {
return queriedValues.filter(val => Boolean(val)).map(queriedValue => {
if (isLanguage(queriedValue)) return languageToLocale(queriedValue, options.locales);
return queriedValue;
}).find(queriedLocale => options.locales.find(locale => locale === queriedLocale)) || options.defaultLocale;
};
const setLocale = (res, locale) => {
res.cookie(options.cookieName, locale, { maxAge: 900000, httpOnly: true });
};
const addSelectedLocaleArgumentIfNotPresent = (args, selectedLocale) => {
if (config.locales.indexOf(args[args.length -1]) == -1) {
return args.concat(selectedLocale);
}
return args;
};
const api = (selectedLocale) => {
selectedLocale = selectedLocale || options.defaultLocale;
return {
getLocale: () => selectedLocale,
getLanguage: () => localeToLanguage(selectedLocale),
getLocales: () => options.locales,
getLanguages: () => options.locales.map(localeToLanguage),
t: (arg1, arg2, arg3, arg4) => looseTranslate(arg1, arg2, arg3, arg4, selectedLocale),
};
};
const middleware = (req, res, next) => {
const queriedValues =
options.queryParameters.map(param => safeObjVal(req, ['query', param]))
.concat([safeObjVal(req, ['cookies', options.cookieName]),])
.concat(guessFromHeaders(req));
const selectedLocale = findBestLocale(queriedValues);
setLocale(res, selectedLocale);
let selectedApi = api(selectedLocale);
Object.keys(selectedApi).forEach(key => {
res.locals[key] = selectedApi[key];
req[key] = selectedApi[key];
});
next();
};
return {
ready: load(),
middleware: middleware,
api: api,
};
};