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