This repository was archived by the owner on Dec 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (54 loc) · 1.82 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
'use strict';
var fs = require('fs');
var path = require('path');
var po2json = require('po2json');
var Jed = require('jed');
var translators = {};
var poData = {};
function I18NHelper(options) {
this.poFilePath = options.poFilePath;
this.poFileName = options.poFileName || 'messages.po';
this.domain = options.domain;
this.defaultLocale = options.defaultLocale || 'en_US';
}
I18NHelper.prototype = {
loadLocaleData: function (locale) {
if (!translators[locale] && !poData[locale]) {
if (!fs.existsSync(path.join(this.poFilePath, locale, this.poFileName))) {
locale = this.defaultLocale;
}
poData[locale] = po2json.parseFileSync(path.join(this.poFilePath, locale, this.poFileName), {
format: 'jed1.x',
domain: this.domain
});
translators[locale] = new Jed(poData[locale]);
}
},
getTranslator: function (locale) {
this.loadLocaleData(locale);
return translators[locale];
},
getPoData: function (locale) {
this.loadLocaleData(locale);
return poData[locale];
},
getClosestTranslation: function (locale, key) {
var translation = null;
if (this.translationExists(locale, key)) {
translation = this.getTranslator(locale).translate(key);
} else if (this.defaultTranslationExists(key)) {
translation = this.getDefaultTranslation(key);
}
return translation;
},
getDefaultTranslation: function (key) {
return this.getTranslator(this.defaultLocale).translate(key);
},
translationExists: function (locale, key) {
return !!(this.getPoData(locale) && this.getPoData(locale).locale_data[this.domain] && this.getPoData(locale).locale_data[this.domain][key]);
},
defaultTranslationExists: function (key) {
return !!this.getPoData(this.defaultLocale).locale_data[this.domain][key];
}
};
module.exports = I18NHelper;