-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
84 lines (72 loc) · 2.17 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
77
78
79
80
81
82
83
84
const path = require('path')
const flatfile = require('flat-file-db')
const promisify = require('then-flat-file-db')
const escapeRegexp = require('escape-regex')
const Observable = require("zen-observable")
let db
function init(options) {
db = promisify(flatfile.sync(path.resolve(process.cwd(), options.dbName || 'views.db')))
}
// This is here for backwards compatability should be removed at some point
init({dbName: process.env.DB_NAME})
const keyRegex = (str) => {
str = str.split('*').map( s => escapeRegexp(s)).join('*')
return new RegExp('^' + str.replace('*','.*'))
}
let handlers = [];
const observable = new Observable((observer) => {
handlers.push((data) => observer.next(data))
let index = handlers.length;
return () => {
handlers = [...handlers.slice(0, index), ...handlers.slice(index)]
}
});
module.exports = {
options: [
{
name: 'db-name',
description: 'The name of the flat-file-db file.',
defaultValue: process.env.DB_NAME || 'views.db'
}
],
init,
put: (key, value) => {
handlers.forEach(handler => {
handler({key, value});
})
return db.put(key, value)
},
has: (key) => Promise.resolve(db.has(key)),
keys: () => Promise.resolve(db.keys()),
// Get a value and filter it
get: async (key, options) => {
let value
try {
value = await db.get(key)
} catch (err) {
value = { views: [] }
}
return {
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
})
}
},
// Get all values starting with a certain pathname and filter their views
getAll: async function getAll(options) {
const data = {}
const keys = (await module.exports.keys()).filter((key) => {
return options.ignoreWildcard ? key.startsWith(options.pathname) : key.match(keyRegex(options.pathname))
})
for (let key of keys) {
data[key] = await module.exports.get(key, { before: options.before, after: options.after })
}
await Promise.all(keys)
return data
},
subscribe: (cb) => {
return observable.subscribe(cb);
}
}