forked from CruGlobal/serverless-merge-config
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (62 loc) · 1.57 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
'use strict'
const {
assign,
forEach,
isArray,
isObject,
isPlainObject,
unset,
uniq
} = require('lodash')
class ServerlessMergeConfig {
constructor(serverless, options) {
this.serverless = serverless
this.options = options
this.hooks = {
'before:package:initialize': this.mergeConfig.bind(this),
'before:offline:start:init': this.mergeConfig.bind(this),
'before:invoke:local:invoke': this.mergeConfig.bind(this)
}
}
mergeConfig() {
this.deepMerge(this.serverless.service)
}
deepMerge(obj, parent) {
forEach(obj, (value, key, collection) => {
if (isPlainObject(value) || isArray(value)) {
this.deepMerge(value, obj)
}
if (key === '$<<') {
if (isArray(value)) {
value.forEach((subValue) => {
if (parent && isArray(parent)) {
parent.push(subValue);
}
else {
this.assignValue(collection, subValue)
}
})
} else {
this.assignValue(collection, value)
}
unset(obj, key);
// remove invalid values
if (parent && isArray(parent)) {
parent.forEach((value, key) => {
if (!value || (isObject(value) && Object.keys(value).length === 0)) {
parent.splice(key, 1);
}
});
parent = uniq(parent);
}
}
})
}
assignValue(collection, value) {
if (isPlainObject(value)) {
// Only merge objects
assign(collection, value)
}
}
}
module.exports = ServerlessMergeConfig