Skip to content
This repository has been archived by the owner on May 22, 2020. It is now read-only.

Added persistance loading and automatic expiry #3

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you explain, what is the START time ? last write? last read?


## SETUP: `onChange: function`
`onChange(key, value)` is triggered for every change in a model
Expand Down
29 changes: 29 additions & 0 deletions atom.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}

Expand Down