-
Notifications
You must be signed in to change notification settings - Fork 4
/
inject.js
41 lines (38 loc) · 917 Bytes
/
inject.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
'use strict'
var mutexify = require('mutexify')
module.exports = function (store, _codec) {
var codec = _codec || require('flumecodec/json')
var lock = mutexify()
var value
return {
get: function (cb) {
if(value) return cb(null, value)
else store.get(function (err, _value) {
if(err) return cb(err)
try {
value = codec.decode(_value)
} catch (err) {
return cb(err)
}
cb(null, value)
})
},
//only allow one update at a time.
set: function (_value, cb) {
lock(function (unlock) {
store.set(codec.encode(_value), function (err) {
if(!err) value=_value
unlock(cb, err, _value)
})
})
},
destroy: function (cb) {
lock(function (unlock) {
store.destroy(function (err) {
value=null
unlock(cb, err)
})
})
}
}
}