UNPKG

1.7 kBtext/coffeescriptView Raw
1# Copyright (c) 2013 Rod Vagg, MIT License
2setImmediate = global.setImmediate or process.nextTick
3Errors = require("./abstract-error")
4InvalidArgumentError = Errors.InvalidArgumentError
5
6module.exports = class AbstractChainedBatch
7 constructor: (db) ->
8 @_db = db
9 @_operations = []
10 @_written = false
11
12 _checkWritten: ->
13 throw new Error("write() already called on this batch") if @_written
14
15 put: (key, value) ->
16 @_checkWritten()
17 err = @_db._checkKey(key, "key", @_db._isBuffer)
18 throw err if err
19 key = String(key) unless @_db._isBuffer(key)
20 value = String(value) unless @_db._isBuffer(value)
21 if typeof @_put is "function"
22 @_put key, value
23 else
24 @_operations.push
25 type: "put"
26 key: key
27 value: value
28
29 this
30
31 del: (key) ->
32 @_checkWritten()
33 err = @_db._checkKey(key, "key", @_db._isBuffer)
34 throw err if err
35 key = String(key) unless @_db._isBuffer(key)
36 if typeof @_del is "function"
37 @_del key
38 else
39 @_operations.push
40 type: "del"
41 key: key
42
43 this
44
45 clear: ->
46 @_checkWritten()
47 @_operations = []
48 @_clear() if typeof @_clear is "function"
49 this
50
51 write: (options, callback) ->
52 @_checkWritten()
53 callback = options if typeof options is "function"
54 throw new InvalidArgumentError("write() requires a callback argument") unless typeof callback is "function"
55 options = {} unless typeof options is "object"
56 @_written = true
57 return @_write(callback) if typeof @_write is "function"
58 return @_db._batch(@_operations, options, callback) if typeof @_db._batch is "function"
59 setImmediate callback
60