-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
59 lines (51 loc) · 1.31 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
const Storage = require('./lib/storage')
const get = require('./lib/get')
const put = require('./lib/put')
const mutexify = require('mutexify')
const thunky = require('thunky')
module.exports = class Tinystore {
constructor (file) {
this.data = new Storage(file)
this.lock = mutexify()
this.opened = false
this.ready = thunky(open.bind(this))
}
get (key, cb) {
if (!Buffer.isBuffer(key)) key = Buffer.from(key)
if (!this.opened) return openAndGet(this, key, cb)
get(this, key, cb)
}
put (key, value, cb) {
if (!cb) cb = noop
if (!Buffer.isBuffer(key)) key = Buffer.from(key)
if (!this.opened) return openAndPut(this, key, value || null, cb)
if (value && !Buffer.isBuffer(value)) value = Buffer.from(value)
put(this, key, value || null, cb)
}
flush (cb) {
this.ready((err) => {
if (err) return cb(err)
this.lock(unlock => unlock(cb, null))
})
}
}
function noop () {}
function openAndGet (self, key, cb) {
self.ready(function (err) {
if (err) return cb(err)
self.get(key, cb)
})
}
function openAndPut (self, key, value, cb) {
self.ready(function (err) {
if (err) return cb(err)
self.put(key, value, cb)
})
}
function open (cb) {
this.data.open((err) => {
if (err) return cb(err)
this.opened = true
cb(null)
})
}