-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexpiry.js
51 lines (42 loc) · 1.16 KB
/
expiry.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
const { Level } = require('level')
module.exports = Expiry
function Expiry (db) {
if (!(this instanceof Expiry)) return new Expiry(db)
this.db = typeof db === 'string' ? createLevelDB(db) : db
return this
}
Expiry.prototype.set = function (hash, cb) {
const date = new Date()
const iso = date.toISOString()
const ts = Math.floor(date.getTime() / 1000)
const key = `expiry:${iso}:${hash}`
const data = { hash, ts, iso }
this.db.put(key, data, cb)
}
Expiry.prototype.getSince = function (date, cb) {
const list = {}
const iso = new Date(date).toISOString()
const key = `expiry:${iso}:`
const iterator = this.db.iterator({
gte: key,
lt: 'expiry:~'
})
const iterate = () => {
iterator.next((err, key, value) => {
if (err) return cb(err)
if (key && value) {
list[value.hash] = value.ts
iterate() // Recursively fetch next item
} else {
iterator.close((err) => {
if (err) return cb(err)
cb(null, list) // End of iteration
})
}
})
}
iterate() // Start iteration
}
function createLevelDB (location) {
return new Level(location, { valueEncoding: 'json' })
}