Add YAML Support

master
Eric Chan 2019-08-14 10:13:07 -07:00
parent 8963af3a0a
commit 3db636481a
5 changed files with 457 additions and 415 deletions

View File

@ -10,7 +10,7 @@ koa-locales
koa locales, i18n solution for koa:
1. All locales resources location on `options.dirs`.
2. resources file supports: `*.js`, `*.json` and `*.properties`, see [examples](test/locales/).
2. resources file supports: `*.js`, `*.json`, `*.yml`, `*.yaml` and `*.properties`, see [examples](test/locales/).
3. One api: `__(key[, value, ...])`.
4. Auto detect request locale from `query`, `cookie` and `header: Accept-Language`.

View File

@ -9,6 +9,7 @@ const fs = require('fs');
const path = require('path');
const ms = require('humanize-ms');
const assign = require('object-assign');
const yaml = require('js-yaml');
const DEFAULT_OPTIONS = {
defaultLocale: 'en-US',
@ -18,7 +19,7 @@ const DEFAULT_OPTIONS = {
writeCookie: true,
cookieMaxAge: '1y',
dir: undefined,
dirs: [ path.join(process.cwd(), 'locales') ],
dirs: [path.join(process.cwd(), 'locales')],
functionName: '__',
};
@ -62,6 +63,8 @@ module.exports = function (app, options) {
resource = flattening(require(filepath));
} else if (name.endsWith('.properties')) {
resource = ini.parse(fs.readFileSync(filepath, 'utf8'));
} else if (name.endsWith('.yml') || name.endsWith('.yaml')) {
resource = flattening(yaml.safeLoad(fs.readFileSync(filepath, 'utf8')));
}
resources[locale] = resources[locale] || {};
@ -122,7 +125,7 @@ module.exports = function (app, options) {
// __(locale, key, value1, ...)
const args = new Array(arguments.length - 1);
args[0] = text;
for(let i = 2; i < arguments.length; i++) {
for (let i = 2; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
return util.format.apply(util, args);
@ -145,7 +148,7 @@ module.exports = function (app, options) {
}
const args = new Array(arguments.length + 1);
args[0] = locale;
for(let i = 0; i < arguments.length; i++) {
for (let i = 0; i < arguments.length; i++) {
args[i + 1] = arguments[i];
}
return gettext.apply(this, args);
@ -293,8 +296,8 @@ function flattening(data) {
const result = {};
function deepFlat (data, keys) {
Object.keys(data).forEach(function(key) {
function deepFlat(data, keys) {
Object.keys(data).forEach(function (key) {
const value = data[key];
const k = keys ? keys + '.' + key : key;
if (isObject(value)) {

View File

@ -18,6 +18,8 @@
"debug": "^2.6.0",
"humanize-ms": "^1.2.0",
"ini": "^1.3.4",
"js-yaml": "^3.13.1",
"npminstall": "^3.23.0",
"object-assign": "^4.1.0"
},
"devDependencies": {

View File

@ -38,11 +38,11 @@ describe('koa-locales.test.js', function () {
.expect(200, done);
});
it('should not set locale cookie after header sent', function(done) {
it('should not set locale cookie after header sent', function (done) {
request(app.callback())
.get('/headerSent')
.expect('foo')
.expect(200, function(err) {
.expect(200, function (err) {
assert(!err, err && err.message);
setTimeout(done, 50);
});
@ -278,8 +278,8 @@ describe('koa-locales.test.js', function () {
'gender': '性别',
'name': '姓名',
})
.expect(function(res) {
if(res.headers['set-cookie'] || res.headers['Set-Cookie']){
.expect(function (res) {
if (res.headers['set-cookie'] || res.headers['Set-Cookie']) {
throw new Error('should not write cookie');
}
})
@ -501,6 +501,35 @@ describe('koa-locales.test.js', function () {
.expect(200, done);
});
it('should mock acceptsLanguages return string', function (done) {
mm(app.request, 'acceptsLanguages', function () {
return 'fr';
});
request(app.callback())
.get('/?locale=fr')
.set('Accept-Language', 'fr;q=0.8, fr, fr')
.expect({
email: 'le email',
hello: 'fengmk2, Comment allez-vous',
message: 'Hello fengmk2, how are you today? How was your 18.',
empty: '',
notexists_key: 'key not exists',
empty_string: '',
empty_value: '',
novalue: 'key %s ok',
arguments3: '1 2 3',
arguments4: '1 2 3 4',
arguments5: '1 2 3 4 5',
arguments6: '1 2 3 4 5. 6',
values: 'foo bar foo bar {2} {100}',
object: 'foo bar foo bar {z}',
gender: 'le sexe',
name: 'prénom',
})
.expect('Set-Cookie', /^locale=fr; path=\/; expires=\w+/)
.expect(200, done);
});
it('should mock acceptsLanguages return null', function (done) {
mm(app.request, 'acceptsLanguages', function () {
return null;
@ -530,7 +559,7 @@ describe('koa-locales.test.js', function () {
});
});
describe('__getLocale and __getLocaleOrigin', function() {
describe('__getLocale and __getLocaleOrigin', function () {
it('should __getLocale and __getLocaleOrigin from cookie', function () {
return request(app.callback())
.get('/origin')
@ -558,7 +587,7 @@ describe('koa-locales.test.js', function () {
});
});
describe('__setLocale', function() {
describe('__setLocale', function () {
it('should set locale and cookie', function () {
return request(app.callback())
.get('/set')
@ -606,7 +635,7 @@ function createApp(options) {
if (this.url === '/headerSent') {
this.body = 'foo';
const that = this;
setTimeout(function() {
setTimeout(function () {
that[fname]('Email');
}, 10);
return;
@ -628,7 +657,7 @@ function createApp(options) {
arguments5: this[fname]('%s %s %s %s %s', 1, 2, 3, 4, 5),
arguments6: this[fname]('%s %s %s %s %s.', 1, 2, 3, 4, 5, 6),
values: this[fname]('{0} {1} {0} {1} {2} {100}', ['foo', 'bar']),
object: this[fname]('{foo} {bar} {foo} {bar} {z}', {foo: 'foo', bar: 'bar'}),
object: this[fname]('{foo} {bar} {foo} {bar} {z}', { foo: 'foo', bar: 'bar' }),
};
});

8
test/locales/fr.yml Normal file
View File

@ -0,0 +1,8 @@
Email: "le email"
emptyValue: ""
Hello %s, how are you today?: "%s, Comment allez-vous"
model:
user:
fields:
name: "prénom"
gender: "le sexe"