From 7b516f18dd84055f330a44a596bc7fc68c6f2c31 Mon Sep 17 00:00:00 2001 From: Anton Golub Date: Wed, 3 May 2023 17:25:46 +0300 Subject: [PATCH] fix: use jsonClone to fix cache layer (#174) * fix: fix jsonClone to fix cache layer * test: add test for caching layer --- lib/read-json.js | 9 +++--- test/cache.js | 53 +++++++++++++++++++++++++++++++++++ test/fixtures/deepnested.json | 15 ++++++++++ 3 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 test/cache.js create mode 100644 test/fixtures/deepnested.json diff --git a/lib/read-json.js b/lib/read-json.js index 3dec3a0..aaf24e9 100644 --- a/lib/read-json.js +++ b/lib/read-json.js @@ -67,13 +67,15 @@ function jsonClone (obj) { } else if (Array.isArray(obj)) { var newarr = new Array(obj.length) for (var ii in obj) { - newarr[ii] = obj[ii] + newarr[ii] = jsonClone(obj[ii]) } + return newarr } else if (typeof obj === 'object') { var newobj = {} for (var kk in obj) { - newobj[kk] = jsonClone[kk] + newobj[kk] = jsonClone(obj[kk]) } + return newobj } else { return obj } @@ -115,7 +117,6 @@ function parseJson (file, er, d, log, strict, cb) { return cb(parseError(jsonErr, file)) } } - extrasCached(file, d, data, log, strict, cb) } @@ -505,7 +506,7 @@ function final (file, data, log, strict, cb) { } function fillTypes (file, data, cb) { - var index = data.main ? data.main : 'index.js' + var index = data.main || 'index.js' if (typeof index !== 'string') { return cb(new TypeError('The "main" attribute must be of type string.')) diff --git a/test/cache.js b/test/cache.js new file mode 100644 index 0000000..c42d2fb --- /dev/null +++ b/test/cache.js @@ -0,0 +1,53 @@ +var path = require('path') + +var tap = require('tap') + +var readJson = require('../') +var file = path.resolve(__dirname, 'fixtures/deepnested.json') + +tap.test('cache test', function (t) { + var count = 0 + var spy = function (file_, data_, then) { + count++ + then() + } + + readJson.extraSet.push(spy) + t.teardown(function () { + readJson.extraSet.pop() + }) + + readJson(file, function (er, data) { + if (er) { + throw er + } + var expectedProp = [ + { + prop: { + prop: [ + { + prop: 'prop', + }, + ], + }, + }, + ] + t.ok(data) + t.equal(data.name, 'deep-nested') + t.equal(data.version, '1.2.3') + t.equal(data._id, data.name + '@' + data.version) + t.same(data.prop, expectedProp) + + data.prop = null + + readJson(file, function (er2, data2) { + if (er2) { + throw er2 + } + t.same(data2.prop, expectedProp) + t.not(data2.prop, data.prop) + t.equal(count, 1) + t.end() + }) + }) +}) diff --git a/test/fixtures/deepnested.json b/test/fixtures/deepnested.json new file mode 100644 index 0000000..b389f66 --- /dev/null +++ b/test/fixtures/deepnested.json @@ -0,0 +1,15 @@ +{ + "name": "deep-nested", + "version": "1.2.3", + "prop": [ + { + "prop": { + "prop": [ + { + "prop": "prop" + } + ] + } + } + ] +}