2018-03-24 01:37:32 +00:00
|
|
|
/* eslint-env node */
|
2018-07-21 19:00:08 +00:00
|
|
|
/* global log */
|
2017-05-15 21:48:19 +00:00
|
|
|
|
2018-03-24 01:37:32 +00:00
|
|
|
exports.setup = (locale, messages) => {
|
|
|
|
if (!locale) {
|
|
|
|
throw new Error('i18n: locale parameter is required');
|
|
|
|
}
|
|
|
|
if (!messages) {
|
|
|
|
throw new Error('i18n: messages parameter is required');
|
|
|
|
}
|
2017-05-15 21:48:19 +00:00
|
|
|
|
2018-03-24 01:37:32 +00:00
|
|
|
function getMessage(key, substitutions) {
|
|
|
|
const entry = messages[key];
|
|
|
|
if (!entry) {
|
2018-07-21 19:00:08 +00:00
|
|
|
log.error(
|
2018-04-27 21:25:04 +00:00
|
|
|
`i18n: Attempted to get translation for nonexistent key '${key}'`
|
|
|
|
);
|
2018-03-24 01:37:32 +00:00
|
|
|
return '';
|
|
|
|
}
|
2017-04-04 06:32:46 +00:00
|
|
|
|
2018-03-24 01:37:32 +00:00
|
|
|
const { message } = entry;
|
2018-04-05 19:39:16 +00:00
|
|
|
if (Array.isArray(substitutions)) {
|
2018-03-24 01:37:32 +00:00
|
|
|
return substitutions.reduce(
|
|
|
|
(result, substitution) => result.replace(/\$.+?\$/, substitution),
|
|
|
|
message
|
|
|
|
);
|
|
|
|
} else if (substitutions) {
|
|
|
|
return message.replace(/\$.+?\$/, substitutions);
|
|
|
|
}
|
|
|
|
|
|
|
|
return message;
|
|
|
|
}
|
|
|
|
|
|
|
|
getMessage.getLocale = () => locale;
|
|
|
|
|
|
|
|
return getMessage;
|
|
|
|
};
|