enonic / lib-cache

Cache Library for Enonic XP.
Apache License 2.0
2 stars 1 forks source link

Direct reference to stored cache object #5

Open Pdrevland opened 5 years ago

Pdrevland commented 5 years ago
...
function getObject() { return { a: { b: true } }; }
var o = cache.get('object', getObject);
o.a.b // => true
o.a = { b: false }
var p = cache.get('object', getObject);
// expected p.a.b => true
p.a.b // => false
...

The expected behaviour of the stored cache object should be what the cache function returns. Problem probably lies in that the stored cache object being returned as reference rather than value, as is normal JS behaviour, and mutation of non-primitives mutates the reference value.

Easy solution is to clearly state this behaviour in the docs as this might lead to some confusion.

ComLock commented 3 years ago

Came across this same problem today. Here is some test code you can put in main.es

import {newCache} from '/lib/cache';
const cache = newCache({
    size: 1,
    expire: 3600
});
function getCached() {
        // If you surround this with JSON.parse(JSON.stringify()) the "MISFEATURE" goes away.
    return cache.get('a', () => {
        return {
            propertyName: 'propertyValue'
        };
    });
}
const obj = getCached();
log.info(`obj:${toStr(obj)}`);
obj.propertyName = 'changed';
log.info(`modified obj outside cache:${toStr(obj)}`);
const obj2 = getCached();
log.info(`from cache:${toStr(obj2)}`);
rymsha commented 3 years ago

This is a documentation issue. Developers are responsible to take care of immutability of cached objects themselves.