/
config_object.js
55 lines (45 loc) · 1.15 KB
/
config_object.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
const objectify = require('../utils/objectify')
const deepAssign = require('../utils/deep_assign')
const deepMerge = require('../utils/deep_merge')
const { isStrPath, prettyPrint } = require('../utils/helpers')
/**
* @class
* @extends { Object }
*/
class ConfigObject extends Object {
constructor(props = {}) {
super()
this.merge(props)
}
get(key) {
return isStrPath(key) ? objectify(key, this) : this[key]
}
set(key, value) {
Object.assign(this, deepAssign(this, key, value))
return this
}
delete(key) {
let obj = this
let propKey = key
if (isStrPath(key)) {
const keys = key.split('.')
propKey = keys.pop()
const parentObjPath = keys.join('.')
obj = objectify(parentObjPath, this)
}
if (!obj) throw new Error(`Prop not found: ${key} in ${prettyPrint(obj)}`)
delete obj[propKey]
return this
}
toObject() {
const object = {}
/* eslint no-return-assign: 0 */
Object.keys(this).forEach((key) => (object[key] = this[key]))
return object
}
merge(config) {
Object.assign(this, deepMerge(this, config))
return this
}
}
module.exports = ConfigObject