-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
76 lines (61 loc) · 1.66 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const Observable = require("zen-observable");
let data = {};
let handlers = [];
const escapeRegexp = require('escape-regex')
const keyRegex = (str) => {
str = str.split('*').map( s => escapeRegexp(s)).join('*')
return new RegExp('^' + str.replace('*','.*'))
}
const observable = new Observable(observer => {
handlers.push(data => observer.next(data));
let index = handlers.length;
return () => {
handlers = [...handlers.slice(0, index), ...handlers.slice(index)];
};
});
function get(key, options) {
const value = data[key] || { views: [] };
return Promise.resolve({
views: value.views.filter(view => {
if (options && options.before && view.time > options.before) return false;
if (options && options.after && view.time < options.after) return false;
return true;
})
});
}
function keys() {
return Promise.resolve(Object.keys(data));
}
function put(key, value) {
data[key] = value;
handlers.forEach(handler => {
handler({ key, value });
});
return Promise.resolve();
}
async function getAll(options) {
const value = {};
const _keys = (await keys()).filter(
key =>
options.ignoreWildcard
? key.startsWith(options.pathname)
: key.match(keyRegex(options.pathname))
);
for (let key of _keys) {
value[key] = await get(key, {
before: options.before,
after: options.after
});
}
return Promise.resolve(value);
}
function has(key) {
return Promise.resolve({}.hasOwnProperty.call(data, key));
}
function clear() {
data = {};
}
function subscribe(listener) {
return observable.subscribe(listener);
}
module.exports = { get, put, getAll, has, keys, clear, subscribe };