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