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',
@ -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] || {};

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

@ -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;

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"