diff --git a/README.md b/README.md index 58102ff..3c08e50 100644 --- a/README.md +++ b/README.md @@ -389,6 +389,9 @@ car.set({ engine: '746cc', brand: 'Syrena' }); NOTE: One extra parameter is always added to modelData: `lastStorageUpdateTimestamp`. Feel free to use it for syncing data between tabs. +## SETUP: `persistencePeriod: number` + +A number of milliseconds that the model should be kept. It will be removed when trying to load it from storage for the first time after expiration ## SETUP: `onChange: function` `onChange(key, value)` is triggered for every change in a model diff --git a/atom.js b/atom.js index b908851..cc3a40a 100644 --- a/atom.js +++ b/atom.js @@ -262,6 +262,11 @@ throw new Error('`persistenceLib` property in atom-js model needs to expose `set` method.'); } } + if (config.persistencePeriod) { + if (!config.persistenceLib) { + throw new Error('Persistence expiration needs a persistence library. Please provide a "persistenceLib" property.'); + } + } // Execute the next function in the async queue. function doNext() { if (q) { @@ -573,8 +578,32 @@ me.bind = me.on; me.unbind = me.off; + if (config.persistencePeriod) { + const persistedData = config.persistenceLib.get(config.modelName) || {}; + const lastStorageUpdateTimestamp = persistedData.lastStorageUpdateTimestamp; + if (lastStorageUpdateTimestamp && Date.now() - lastStorageUpdateTimestamp > config.persistencePeriod) { + config.persistenceLib.remove(config.modelName); + } + } + if (args.length) { args[2] = false; // disable initial validation + + var finalMap = {}; + + if (me.persistenceLib) { + Object.assign( + finalMap, + config.persistenceLib.get(config.modelName) + ) + } + + if (isObject(keyOrMap)) { + Object.assign(finalMap, keyOrMap); + } else { + finalMap[args[0]] = args[1]; + } + me.set.apply(me, args); }