-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
104 lines (90 loc) · 2.88 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var deap = require('deap')
var beepboopProvider = require('./lib/beepboop-provider')
var memoryProvider = require('./lib/memory-provider')
var fsProvider = require('./lib/fs-provider')
var Logger = require('./lib/logger')
var providers = {
'memory': memoryProvider,
'beepboop': beepboopProvider,
'fs': fsProvider
}
module.exports = function NewKV (options) {
var config = deap.update({
logger: null, // override logger
provider: null, // select provider strategy explicitly ('memory'||'beepboop'||'fs')
debug: false, // enables logging of calls/errors
serialize: true, // JSON.stringify/parse on set/get
token: process.env.BEEPBOOP_TOKEN, // auth token
url: process.env.BEEPBOOP_PERSIST_URL || process.env.BEEPBOOP_API_URL || 'https://beepboophq.com/api/v1', // persist endpoint
directory: null // only for filesystem provider
}, options || {})
var logger = config.logger || Logger(config.debug)
var provider
// Use provider explicitly set if present and valid
if (Object.keys(providers).indexOf(config.provider) !== -1) {
provider = providers[config.provider](config)
} else {
// Select provider based on configuration present
provider = (!config.token || !config.url) ? memoryProvider(config) : beepboopProvider(config)
}
// return a wrapper around provider to normalize args and logging
return {
type: provider.type,
get: function (key, cb) {
provider.get(key, function (err, value) {
if (err) {
logger.error('Error calling get(%s): %s', key, err.message)
} else {
logger.debug('get(%s)', key)
}
cb(err, value)
})
},
mget: function (keys, cb) {
provider.mget(keys, function (err, value) {
if (err) {
logger.error('Error calling mget([%s]): %s', keys.join(','), err.message)
} else {
logger.debug('mget([%s])', keys.join(','))
}
cb(err, value)
})
},
set: function (key, value, cb) {
cb = cb || noop
provider.set(key, value, function (err, value) {
if (err) {
logger.error('Error calling set(%s): %s', key, err.message)
} else {
logger.debug('set(%s)', key)
}
cb(err, value)
})
},
del: function (key, cb) {
provider.del(key, function (err, value) {
if (err) {
logger.error('Error calling del(%s): %s', key, err.message)
} else {
logger.debug('del(%s)', key)
}
cb(err, value)
})
},
list: function (begins, cb) {
if (typeof begins === 'function') {
cb = begins
begins = null
}
provider.list(begins, function (err, value) {
if (err) {
logger.error('Error calling list(): %s', err.message)
} else {
logger.debug('list()')
}
cb(err, value)
})
}
}
}
function noop () {}