Skip to content
This repository was archived by the owner on Dec 14, 2023. It is now read-only.

Commit eb0b614

Browse files
First implementation of i18n lib
1 parent 44841da commit eb0b614

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

index.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'use strict';
2+
3+
var fs = require('fs');
4+
var path = require('path');
5+
var po2json = require('po2json');
6+
var Jed = require('jed');
7+
var translators = {};
8+
var poData = {};
9+
10+
function I18NHelper(options) {
11+
this.poFilePath = options.poFilePath;
12+
this.poFileName = options.poFileName || 'messages.po';
13+
this.domain = options.domain;
14+
this.defaultLocale = options.defaultLocale || 'en_US';
15+
}
16+
17+
I18NHelper.prototype = {
18+
loadLocaleData: function (locale) {
19+
if (!translators[locale] && !poData[locale]) {
20+
if (!fs.existsSync(path.join(this.poFilePath, locale, this.poFileName))) {
21+
locale = this.defaultLocale;
22+
}
23+
poData[locale] = po2json.parseFileSync(path.join(this.poFilePath, locale, this.poFileName), {
24+
format: 'jed1.x',
25+
domain: this.domain
26+
});
27+
translators[locale] = new Jed(poData[locale]);
28+
}
29+
},
30+
31+
getTranslator: function (locale) {
32+
this.loadLocaleData(locale);
33+
return translators[locale];
34+
},
35+
36+
getPoData: function (locale) {
37+
this.loadLocaleData(locale);
38+
return poData[locale];
39+
},
40+
41+
getClosestTranslation: function (locale, key) {
42+
var translation = null;
43+
if (this.translationExists(locale, key)) {
44+
translation = this.getTranslator(locale).translate(key);
45+
} else if (this.defaultTranslationExists(key)) {
46+
translation = this.getDefaultTranslation(key);
47+
}
48+
return translation;
49+
},
50+
51+
getDefaultTranslation: function (key) {
52+
return this.getTranslator(this.defaultLocale).translate(key);
53+
},
54+
55+
translationExists: function (locale, key) {
56+
return !!(this.getPoData(locale) && this.getPoData(locale).locale_data[this.domain] && this.getPoData(locale).locale_data[this.domain][key]);
57+
},
58+
59+
defaultTranslationExists: function (key) {
60+
return !!this.getPoData(this.defaultLocale).locale_data[this.domain][key];
61+
}
62+
};
63+
64+
module.exports = I18NHelper;

package.json

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"name": "cp-i18n-lib",
3+
"version": "1.0.0",
4+
"description": "A set of i18n helper functions for CoderDojo's community platform",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [
10+
"i18n",
11+
"coderdojo"
12+
],
13+
"author": "",
14+
"license": "MIT",
15+
"dependencies": {
16+
"jed": "^1.1.0",
17+
"po2json": "^0.4.2"
18+
}
19+
}

0 commit comments

Comments
 (0)