Merge pull request #12 from hotoo/imporve-nested

refact(nested-data): transform nested data on load localization data.
master
fengmk2 2015-09-18 16:15:26 +08:00
commit 04bb9daf8f
2 changed files with 28 additions and 18 deletions

View File

@ -21,7 +21,7 @@ koa-locales
koa locales, i18n solution for koa:
1. All locales resources location on `options.dir`.
2. resources file supports: `*.js`, `*.json` and `*.properties`, [examples](https://github.com/koajs/locales/tree/master/test/locales)
2. resources file supports: `*.js`, `*.json` and `*.properties`, [examples](test/locales/)
3. One api: `__(key[, value, ...])`
4. Auto detect request locale from `query`, `cookie` and `header: Accept-Language`

View File

@ -53,7 +53,7 @@ module.exports = function (app, options) {
var resource = {};
if (name.endsWith('.js') || name.endsWith('.json')) {
resource = require(filepath);
resource = flattening(require(filepath));
} else if (name.endsWith('.properties')) {
resource = ini.parse(fs.readFileSync(filepath, 'utf8'));
}
@ -63,8 +63,6 @@ module.exports = function (app, options) {
}
}
debug('init locales with %j, got %j resources', options, Object.keys(resources));
var ARRAY_INDEX_RE = /\{(\d+)\}/g;
@ -91,10 +89,6 @@ module.exports = function (app, options) {
});
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
app.context[functionName] = function (key, value) {
if (arguments.length === 0) {
// __()
@ -104,7 +98,7 @@ module.exports = function (app, options) {
var locale = this.__getLocale();
var resource = resources[locale] || {};
var text = resource[key] || getNestedValue(resource, key) || key;
var text = resource[key] || key;
debug('%s: %j => %j', locale, key, text);
if (!text) {
return '';
@ -210,13 +204,29 @@ module.exports = function (app, options) {
// support zh_CN, en_US => zh-CN, en-US
return locale.replace('_', '-').toLowerCase();
}
// fetch nested key, example: model.user.fields.title
function getNestedValue(data, key) {
var keys = key.split('.');
for (var i = 0; typeof data === 'object' && i < keys.length; i++) {
data = data[keys[i]];
}
return data;
}
};
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function flattening(data) {
var result = {};
function deepFlat (data, keys) {
Object.keys(data).forEach(function(key) {
var value = data[key];
var k = keys ? keys + '.' + key : key;
if (isObject(value)) {
deepFlat(value, k);
} else {
result[k] = String(value);
}
});
}
deepFlat(data, '');
return result;
}