-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
60 lines (46 loc) · 1.55 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
60
var _ = require('lodash').runInContext()
module.exports = function(config, cb) {
var store = {}
function ensure(options, cb) {
if (options.name === null || options.name === undefined) return cb(new Error('name is required'))
var name = options.name.toLowerCase()
var value = options.value || 0
var metadata = options.metadata || {}
process.nextTick(function() {
cb(null, store[name] || create({ name: name, value: value, metadata: metadata }))
})
}
function allocate(options, cb) {
var size = options.size || 1
ensure(options, function(err, sequence) {
if (err) return cb(err)
process.nextTick(function() {
sequence.value += size
var block = { next: sequence.value - size + 1, remaining: size }
cb(null, _.chain({})
.defaultsDeep(sequence, block)
.omit(['value'])
.value()
)
})
})
}
function create(options) {
store[options.name] = _.defaultsDeep(options, { value: 0 })
return store[options.name]
}
function remove(options, cb) {
if (options.name === null || options.name === undefined) return cb(new Error('name is required'))
delete store[options.name]
cb()
}
function close(cb) {
cb && cb()
}
cb(null, {
remove: remove,
allocate: allocate,
ensure: ensure,
close: close
})
}