-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
91 lines (81 loc) · 2.58 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
85
86
87
88
89
90
91
module.exports = function(db) {
var counter,
validName = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/
db.initAutoKeys = function(callback) {
if (typeof counter != 'undefined') {
return callback()
}
this.get('~counter', function (err, value) {
if (err) {
if (err.name === 'NotFoundError') {
counter = 0
} else {
throw err
}
} else {
counter = value
}
callback()
})
}
db.newAutoKey = function(callback) {
if (typeof callback != 'function') {
throw new Error("newKey requires a callback function")
}
this.put("~counter", ++counter, function(err) {
callback(err, counter.toString())
})
}
db.putField = function(key, name, value, options, callback) {
if (validName.test(name)) {
this.put(key + ":" + name, value, options, callback)
} else {
throw new Error("Invalid char in field name")
}
}
db.getField = function(key, name, options, callback) {
this.get(key + ":" + name, options, callback)
}
db.delField = function(key, name, options, callback) {
this.del(key + ":" + name, options, callback)
}
db.getRecord = function(key, callback) {
var ret = {}
this.createReadStream({start: key + ':', end: key + ':\xff'})
.on('data', function (data) {
ret[data.key.split(':')[1]] = data.value
})
.on('error', function (err) {
callback(err)
})
.on('end', function (err) {
callback(null, ret)
})
}
db.putRecord = function(key, value, callback) {
var ops = []
Object.keys(value).forEach(function(k) {
ops.push({type: 'put', key: key + ":" + k, value: value[k]})
})
this.batch(ops, function (err) {
callback(err)
})
}
db.delRecord = function(key, callback) {
var ops = []
var db = this
this.createReadStream({start: key + ':', end: key + ':\xff'})
.on('data', function (data) {
ops.push({type: 'del', key: data.key})
})
.on('error', function (err) {
callback(err)
})
.on('end', function (err) {
db.batch(ops, function (err) {
if (err) return callback(err)
callback()
})
})
}
}