This repository has been archived by the owner on Jul 19, 2024. It is now read-only.
forked from bitcoinjs/indexd
-
Notifications
You must be signed in to change notification settings - Fork 6
/
dbwrapper.js
85 lines (67 loc) · 2.06 KB
/
dbwrapper.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
85
let typeforce = require('typeforce')
let NIL = Buffer.alloc(0)
function atomic () {
let batch = this.batch()
return {
del: del.bind(batch),
put: put.bind(batch),
write: (callback) => batch.write(callback)
}
}
function del (type, key, callback) {
typeforce(type.keyType, key)
key = type.key.encode(key)
return this.del(key, callback)
}
function get (type, key, callback) {
typeforce(type.keyType, key)
key = type.key.encode(key)
this.get(key, (err, value) => {
if (err && (/NotFound/).test(err)) return callback()
if (err) return callback(err)
if (!type.value) return callback()
callback(null, type.value.decode(value))
})
}
function put (type, key, value, callback) {
typeforce(type.keyType, key)
typeforce(type.valueType, value)
key = type.key.encode(key)
value = type.value ? type.value.encode(value) : NIL
return this.put(key, value, callback)
}
function iterator (type, options, forEach, callback) {
typeforce({
gt: typeforce.maybe(type.keyType),
gte: typeforce.maybe(type.keyType),
lt: typeforce.maybe(type.keyType),
lte: typeforce.maybe(type.keyType),
limit: typeforce.maybe(typeforce.UInt53)
}, options)
// don't mutate
options = Object.assign({}, options)
options.gt = options.gt && type.key.encode(options.gt)
options.gte = options.gte && type.key.encode(options.gte)
options.lt = options.lt && type.key.encode(options.lt)
options.lte = options.lte && type.key.encode(options.lte)
let iterator = this.iterator(options)
function loop (err, key, value) {
// NOTE: ignores .end errors, if they occur
if (err) return iterator.end(() => callback(err))
if (key === undefined || value === undefined) return iterator.end(callback)
key = type.key.decode(key)
value = type.value ? type.value.decode(value) : null
forEach(key, value)
iterator.next(loop)
}
iterator.next(loop)
}
module.exports = function wrap (db) {
return {
atomic: atomic.bind(db),
del: del.bind(db),
get: get.bind(db),
iterator: iterator.bind(db),
put: put.bind(db)
}
}