main
1"use strict";
2
3const _ = require("lodash");
4const glob = require("glob");
5const path = require("path");
6const fs = require("fs");
7const yaml = require("yaml-js");
8
9class I18nLoader {
10 constructor(localesPath, pattern) {
11 this.localesPath = localesPath || '';
12 this.pattern = pattern || "**/*.yml";
13 }
14
15 fetch() {
16 let content = {};
17 _.forEach(glob.sync(this.pattern, { cwd: this.localesPath }), (file) => {
18 let translations = this.fromFile(file);
19 _.forEach(translations, (pairs, locale) => {
20 if (!content[locale]) { content[locale] = {}; }
21 _.assign(content[locale], pairs);
22 });
23 });
24 return content;
25 }
26
27 fromFile(file) {
28 let content = yaml.load(fs.readFileSync(path.join(this.localesPath, file)));
29 _.forEach(content, (data, locale) => {
30 content[locale] = I18nLoader.flatten(data);
31 });
32 return content;
33 }
34
35 static flatten(data, prefix = null) {
36 let result = [];
37 _.forEach(data, (value, key) => {
38 let prefixKey = prefix ? `${prefix}.${key}` : key;
39 if (_.isPlainObject(value)) {
40 _.assign(result, I18nLoader.flatten(value, prefixKey));
41 } else {
42 result[prefixKey] = value;
43 }
44 });
45 return result;
46 }
47}
48
49module.exports = I18nLoader;