UNPKG

1.46 kBJavaScriptView Raw
1var WriteError = require('level-errors').WriteError
2var promisify = require('./promisify')
3var getCallback = require('./common').getCallback
4var getOptions = require('./common').getOptions
5
6function Batch (levelup) {
7 this._levelup = levelup
8 this.batch = levelup.db.batch()
9 this.ops = []
10 this.length = 0
11}
12
13Batch.prototype.put = function (key, value) {
14 try {
15 this.batch.put(key, value)
16 } catch (e) {
17 throw new WriteError(e)
18 }
19
20 this.ops.push({ type: 'put', key: key, value: value })
21 this.length++
22
23 return this
24}
25
26Batch.prototype.del = function (key) {
27 try {
28 this.batch.del(key)
29 } catch (err) {
30 throw new WriteError(err)
31 }
32
33 this.ops.push({ type: 'del', key: key })
34 this.length++
35
36 return this
37}
38
39Batch.prototype.clear = function () {
40 try {
41 this.batch.clear()
42 } catch (err) {
43 throw new WriteError(err)
44 }
45
46 this.ops = []
47 this.length = 0
48
49 return this
50}
51
52Batch.prototype.write = function (options, callback) {
53 var levelup = this._levelup
54 var ops = this.ops
55 var promise
56
57 callback = getCallback(options, callback)
58
59 if (!callback) {
60 callback = promisify()
61 promise = callback.promise
62 }
63
64 options = getOptions(options)
65
66 try {
67 this.batch.write(options, function (err) {
68 if (err) { return callback(new WriteError(err)) }
69 levelup.emit('batch', ops)
70 callback()
71 })
72 } catch (err) {
73 throw new WriteError(err)
74 }
75
76 return promise
77}
78
79module.exports = Batch