From cc81fbda187367e07e071b71bdaa00aaa9d1bd10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=B2=E8=80=98=E2=84=A2?= Date: Fri, 18 Sep 2015 15:14:38 +0800 Subject: [PATCH] refact(nested-data): transform nested data on load localization data. --- README.md | 2 +- index.js | 44 +++++++++++++++++++++++++++----------------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 7352959..75ce5fe 100644 --- a/README.md +++ b/README.md @@ -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` diff --git a/index.js b/index.js index 6e25853..05a0582 100644 --- a/index.js +++ b/index.js @@ -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; +}