forked from ipfs/js-ipfs-repo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.js
More file actions
108 lines (97 loc) · 2.67 KB
/
config.js
File metadata and controls
108 lines (97 loc) · 2.67 KB
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
105
106
107
108
'use strict'
const Key = require('interface-datastore').Key
const queue = require('async/queue')
const waterfall = require('async/waterfall')
const _get = require('lodash.get')
const _set = require('lodash.set')
const _has = require('lodash.has')
const Buffer = require('safe-buffer').Buffer
const configKey = new Key('config')
module.exports = (store) => {
const setQueue = queue(_doSet, 1)
const configStore = {
/**
* Get the current configuration from the repo.
*
* @param {String} key - the config key to get
* @param {function(Error, Object)} callback
* @returns {void}
*/
get (key, callback) {
if (typeof key === 'function') {
callback = key
key = undefined
}
if (!key) {
key = undefined
}
store.get(configKey, (err, encodedValue) => {
if (err) { return callback(err) }
let config
try {
config = JSON.parse(encodedValue.toString())
} catch (err) {
return callback(err)
}
if (key !== undefined && !_has(config, key)) {
return callback(new Error('Key ' + key + ' does not exist in config'))
}
const value = key !== undefined ? _get(config, key) : config
callback(null, value)
})
},
/**
* Set the current configuration for this repo.
*
* @param {String} key - the config key to be written
* @param {Object} value - the config value to be written
* @param {function(Error)} callback
* @returns {void}
*/
set (key, value, callback) {
if (typeof value === 'function') {
callback = value
value = key
key = undefined
} else if (!key || typeof key !== 'string') {
return callback(new Error('Invalid key type'))
}
if (value === undefined || Buffer.isBuffer(value)) {
return callback(new Error('Invalid value type'))
}
setQueue.push({
key: key,
value: value
}, callback)
},
/**
* Check if a config file exists.
*
* @param {function(Error, bool)} callback
* @returns {void}
*/
exists (callback) {
store.has(configKey, callback)
}
}
return configStore
function _doSet (m, callback) {
const key = m.key
const value = m.value
if (key) {
waterfall(
[
(cb) => configStore.get(cb),
(config, cb) => cb(null, _set(config, key, value)),
_saveAll
],
callback)
} else {
_saveAll(value, callback)
}
}
function _saveAll (config, callback) {
const buf = Buffer.from(JSON.stringify(config, null, 2))
store.put(configKey, buf, callback)
}
}