|
| 1 | +const path = require('path') |
| 2 | +const flatfile = require('flat-file-db') |
| 3 | +const promisify = require('then-flat-file-db') |
| 4 | +const escapeRegexp = require('escape-regex') |
| 5 | +const Observable = require("zen-observable") |
| 6 | + |
| 7 | +let db |
| 8 | + |
| 9 | +function init(options) { |
| 10 | + db = promisify(flatfile.sync(path.resolve(process.cwd(), options.dbName || 'views.db'))) |
| 11 | +} |
| 12 | + |
| 13 | +// This is here for backwards compatability should be removed at some point |
| 14 | +init({dbName: process.env.DB_NAME}) |
| 15 | + |
| 16 | +const keyRegex = (str) => { |
| 17 | + str = str.split('*').map( s => escapeRegexp(s)).join('*') |
| 18 | + return new RegExp('^' + str.replace('*','.*')) |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +let handlers = []; |
| 23 | + |
| 24 | +const observable = new Observable((observer) => { |
| 25 | + handlers.push((data) => observer.next(data)) |
| 26 | + let index = handlers.length; |
| 27 | + return () => { |
| 28 | + handlers = [...handlers.slice(0, index), ...handlers.slice(index)] |
| 29 | + } |
| 30 | +}); |
| 31 | + |
| 32 | +module.exports = { |
| 33 | + options: [ |
| 34 | + { |
| 35 | + name: 'db-name', |
| 36 | + description: 'The name of the flat-file-db file.', |
| 37 | + defaultValue: process.env.DB_NAME || 'views.db' |
| 38 | + } |
| 39 | + ], |
| 40 | + init, |
| 41 | + put: (key, value) => { |
| 42 | + handlers.forEach(handler => { |
| 43 | + handler({key, value}); |
| 44 | + }) |
| 45 | + return db.put(key, value) |
| 46 | + }, |
| 47 | + has: (key) => Promise.resolve(db.has(key)), |
| 48 | + keys: () => Promise.resolve(db.keys()), |
| 49 | + // Get a value and filter it |
| 50 | + get: async (key, options) => { |
| 51 | + let value |
| 52 | + try { |
| 53 | + value = await db.get(key) |
| 54 | + } catch (err) { |
| 55 | + value = { views: [] } |
| 56 | + } |
| 57 | + |
| 58 | + return { |
| 59 | + views: value.views.filter(view => { |
| 60 | + if (options && options.before && view.time > options.before) return false |
| 61 | + if (options && options.after && view.time < options.after) return false |
| 62 | + return true |
| 63 | + }) |
| 64 | + } |
| 65 | + }, |
| 66 | + // Get all values starting with a certain pathname and filter their views |
| 67 | + getAll: async function getAll(options) { |
| 68 | + const data = {} |
| 69 | + const keys = (await module.exports.keys()).filter((key) => { |
| 70 | + return options.ignoreWildcard ? key.startsWith(options.pathname) : key.match(keyRegex(options.pathname)) |
| 71 | + }) |
| 72 | + |
| 73 | + for (let key of keys) { |
| 74 | + data[key] = await module.exports.get(key, { before: options.before, after: options.after }) |
| 75 | + } |
| 76 | + |
| 77 | + await Promise.all(keys) |
| 78 | + |
| 79 | + return data |
| 80 | + }, |
| 81 | + subscribe: (cb) => { |
| 82 | + return observable.subscribe(cb); |
| 83 | + } |
| 84 | +} |
0 commit comments