borisdiakur / memoize-fs

memoize/cache in file system solution for Node.js
https://www.npmjs.org/package/memoize-fs
MIT License
36 stars 13 forks source link

Reusable variables are serialized incorrectly #307

Open DiFuks opened 3 weeks ago

DiFuks commented 3 weeks ago
const cachePath = FIXTURE_CACHE
const memoize = memoizeFs({ cachePath })

const reuse = {
  hello: 'world'
}

const memoizedFn = await memoize.fn(() => {
  return {
    a: reuse,
    b: reuse,
  }
});

const result = await memoizedFn();

assert.strictEqual(result.a.hello, 'world');
assert.strictEqual(result.b.hello, 'world'); // ok

const result2 = await memoizedFn();

assert.strictEqual(result2.a.hello, 'world');
assert.strictEqual(result2.b.hello, 'world'); // Cannot read properties of undefined (reading 'hello')

Could you tell me if this is expected behavior? The documentation states that "By default we use basic JSON.stringify and JSON.parse", but the problem is solved when I replace the code with the following:

const cachePath = FIXTURE_CACHE
const memoize = memoizeFs({ cachePath, serialize: JSON.stringify, deserialize: val => JSON.parse(val).data })

const reuse = {
  hello: 'world'
}

const memoizedFn = await memoize.fn(() => {
  return {
    a: reuse,
    b: reuse,
  }
});

const result = await memoizedFn();

assert.strictEqual(result.a.hello, 'world');
assert.strictEqual(result.b.hello, 'world'); // ok

const result2 = await memoizedFn();

assert.strictEqual(result2.a.hello, 'world');
assert.strictEqual(result2.b.hello, 'world'); // ok
DiFuks commented 3 weeks ago

https://github.com/borisdiakur/memoize-fs/blob/1414391cd3c5498e6bc848044be85b592c71ac1d/src/index.ts#L32

As I understand, the problem arises here. A repeated reference to an object is identified as a cyclical reference.

But this is not entirely accurate. There is no cyclical referencing in this situation.