Open Pdrevland opened 5 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)}`);
This is a documentation issue. Developers are responsible to take care of immutability of cached objects themselves.
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.