UNPKG

keyv-nedb-core

Version:
75 lines (69 loc) 2.27 kB
const promisify = require('util').promisify const Datastore = require('nedb-core') const JSONB = require('json-buffer') const prop = (p) => (x) => x == null ? undefined : x[p] const always = (v) => () => v function KeyvNedbCore (options, deserialize) { this.deserialize = deserialize || JSONB.parse this.nedb = new Datastore(options) this.opsCount = 0 if (options && typeof options.automaticEviction === 'number' && options.automaticEviction > 0) { this.autoEvict = options.automaticEviction } else { this.autoEvict = false } this.dbaccess = { find: promisify(this.nedb.find.bind(this.nedb)), findOne: promisify(this.nedb.findOne.bind(this.nedb)), remove: promisify(this.nedb.remove.bind(this.nedb)), update: promisify(this.nedb.update.bind(this.nedb)) } } function getOpsChain (obj) { ++obj.opsCount let chain = Promise.resolve(true) if (obj.autoEvict && obj.opsCount >= obj.autoEvict) { chain = chain.then(() => obj.evictExpired()) } return chain } KeyvNedbCore.prototype = { clear () { this.opsCount = 0 return this.dbaccess.remove({}, { multi: true }).then(always(undefined)) }, delete (key) { return getOpsChain(this) .then(() => this.dbaccess.findOne({ key })) .then((v) => { let ret = true if (!v) { ret = false } return this.dbaccess.remove({ key }).then(always(ret)) }) }, get (key) { return getOpsChain(this).then(() => this.dbaccess.findOne({ key })).then(prop('value')) }, set (key, value) { return getOpsChain(this).then(() => this.dbaccess.update({ key }, { key, value }, { upsert: true })).then(always(true)) }, evictExpired () { this.opsCount = 0 return this.dbaccess.find({}).then(docs => { let acts = [] for (let doc of docs) { let value = (typeof doc.value === 'string') ? this.deserialize(doc.value) : doc if (value == null) { continue } if (typeof value.expires === 'number' && Date.now() > value.expires) { acts.push(this.delete(doc.key)) } } return Promise.all(acts).then(always(true)) }) } } module.exports = KeyvNedbCore