65 lines
1.3 KiB
JavaScript
65 lines
1.3 KiB
JavaScript
|
|
const _ = require('underscore');
|
||
|
|
const state = require('./state.js');
|
||
|
|
|
||
|
|
let cache = {};
|
||
|
|
|
||
|
|
function i (id) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
state.create(id);
|
||
|
|
state.read(id)
|
||
|
|
.then(data => {
|
||
|
|
cache[id] = data;
|
||
|
|
resolve();
|
||
|
|
})
|
||
|
|
.catch(err => reject(err));
|
||
|
|
});
|
||
|
|
}
|
||
|
|
function c (id) {
|
||
|
|
if(_.has(cache, id)) {
|
||
|
|
state.update(id, cache[id]);
|
||
|
|
console.info(`[${id}] Committed new state`);
|
||
|
|
} else {
|
||
|
|
console.error(`[${id}] Could not commit nonexistant state`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
function r (id) {
|
||
|
|
state.read(id)
|
||
|
|
.then(data => {
|
||
|
|
cache[id] = data
|
||
|
|
console.info(`[${id}] Reverted state`);
|
||
|
|
})
|
||
|
|
.catch(console.error);
|
||
|
|
}
|
||
|
|
function e (id) {
|
||
|
|
if(_.has(cache, id)) {
|
||
|
|
delete cache[id];
|
||
|
|
console.info(`[${id}] Erased state`);
|
||
|
|
state.delete(id);
|
||
|
|
} else {
|
||
|
|
console.error(`[${id}] Could not erase nonexistant state`);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
function s (id) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
if(_.has(cache, id)) {
|
||
|
|
resolve(cache[id]);
|
||
|
|
} else {
|
||
|
|
state.read(id)
|
||
|
|
.then(data => {
|
||
|
|
cache[id] = data;
|
||
|
|
console.info(`[${id}] read and cached state`);
|
||
|
|
resolve(cache[id]);
|
||
|
|
})
|
||
|
|
.catch(err => reject(err));
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
module.exports = {
|
||
|
|
init: i,
|
||
|
|
commit: c,
|
||
|
|
revert: r,
|
||
|
|
erase: e,
|
||
|
|
state: s
|
||
|
|
}
|