From 4ed2477a68864a66ecd5d58b6a34186fbea8abe3 Mon Sep 17 00:00:00 2001 From: Iuri Wollmann Date: Sat, 5 Mar 2022 15:43:06 -0300 Subject: [PATCH] Enabled array on .get configurations --- lib/config.js | 14 +++++++++++++- test/confit-test.js | 17 ++++++++++++++++- test/fixtures/config/config.json | 4 ++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/config.js b/lib/config.js index 2b81f58..efa9d31 100644 --- a/lib/config.js +++ b/lib/config.js @@ -31,15 +31,27 @@ class Config { key = key.split(':'); obj = this._store; + var isArray = false; while (obj && key.length) { + if (isArray) { + var idx = Number(key[0]); + if (Number.isInteger(idx) && idx >= 0) { + if (obj.length <= idx) return undefined; + + obj = obj[key.shift()]; + } + } + if (obj.constructor !== Object) { // Do not allow traversal into complex types, // such as Buffer, Date, etc. So, this type // of key will fail: 'foo:mystring:length' return undefined; - } + } + obj = obj[key.shift()]; + isArray = Array.isArray(obj); } return obj; diff --git a/test/confit-test.js b/test/confit-test.js index 2b41f47..06c634b 100644 --- a/test/confit-test.js +++ b/test/confit-test.js @@ -26,11 +26,13 @@ test('confit', function (t) { t.test('get', function (t) { + var basedir; //setting process.env.env to development, should not change 'env:env'. //This should be ignored and 'env:env' should solely depend on process.env.NODE_ENV process.env.env = 'development'; + basedir = path.join(__dirname, 'fixtures', 'config'); - confit().create(function (err, config) { + confit(basedir).create(function (err, config) { var val; t.error(err); @@ -71,6 +73,19 @@ test('confit', function (t) { val = config.get(false); t.equal(typeof val, 'undefined'); + val = config.get('arr'); + t.equal(typeof val, 'object'); + t.equal(Array.isArray(val), true); + + val = config.get('arr:0:name'); + t.equal(val, 'object1'); + + val = config.get('arr_empty:0'); + t.equal(typeof val, 'undefined'); + + val = config.get('arr_empty:0:name'); + t.equal(typeof val, 'undefined'); + t.end(); }); }); diff --git a/test/fixtures/config/config.json b/test/fixtures/config/config.json index 0523b26..b5cad9e 100644 --- a/test/fixtures/config/config.json +++ b/test/fixtures/config/config.json @@ -11,5 +11,9 @@ } }, "value": false, + "arr":[{ + "name": "object1" + }], + "arr_empty":[], "imported": "import:./child.json" } \ No newline at end of file