UNPKG

@boost/translate

Version:

Package and application level translations made easy.

89 lines (84 loc) 2.5 kB
import { Contract, Path, json, yaml } from '@boost/common'; import { importAbsoluteModule } from '@boost/internal'; import { TranslateError } from './TranslateError.mjs'; /* eslint-disable promise/prefer-await-to-callbacks */ /* eslint-disable promise/prefer-await-to-then */ const EXTS = { cjs: ['cjs'], js: ['js'], json: ['json', 'json5'], mjs: ['mjs'], yaml: ['yaml', 'yml'] }; class FileBackend extends Contract { constructor(...args) { super(...args); this.fileCache = new Map(); this.type = 'backend'; this.resources = {}; } init(services, options) { this.configure(options); // Validate resource paths are directories this.options.paths.forEach(path => { if (path.exists() && !path.isDirectory()) { throw new TranslateError('RESOURCE_PATH_INVALID', [path.path()]); } }); } blueprint(schemas) { const array = schemas.array, instance = schemas.instance, string = schemas.string; return { format: string('yaml').oneOf(['cjs', 'js', 'mjs', 'json', 'yaml']), paths: array().of(instance().of(Path, { loose: true }).notNullable()) }; } // istanbul ignore next create() { // We don't need this but is required by the interface } read(locale, namespace, handler) { const _this$options = this.options, format = _this$options.format, paths = _this$options.paths; const resources = {}; Promise.all(paths.map(async path => { await Promise.all(EXTS[format].map(async ext => { const resPath = path.append(locale, `${namespace}.${ext}`); if (!resPath.exists()) { return; } const isCached = this.fileCache.has(resPath); if (!isCached) { let content; switch (ext) { case 'yml': case 'yaml': content = yaml.load(resPath); break; case 'json': case 'json5': content = json.load(resPath); break; default: content = await importAbsoluteModule(resPath.path()); break; } this.fileCache.set(resPath, content); } Object.assign(resources, this.fileCache.get(resPath)); })); })).then(() => { this.resources = resources; handler(null, resources); }).catch(error => { handler(error, {}); }); } } export { FileBackend }; //# sourceMappingURL=FileBackend.mjs.map