dev-sidecar/packages/core/src/config.js

88 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-10-27 13:14:12 +00:00
const Shell = require('./shell')
2020-10-24 13:22:44 +00:00
const lodash = require('lodash')
const defConfig = require('./config/index.js')
2020-10-26 17:12:40 +00:00
let configTarget = lodash.cloneDeep(defConfig)
2020-11-06 10:59:54 +00:00
function _deleteDisabledItem (target) {
lodash.forEach(target, (item, key) => {
if (item == null) {
delete target[key]
2020-10-25 13:04:28 +00:00
}
2020-11-06 10:59:54 +00:00
if (lodash.isObject(item)) {
_deleteDisabledItem(item)
}
})
2020-10-25 13:04:28 +00:00
}
2020-10-27 13:14:12 +00:00
const configApi = {
2020-10-24 13:22:44 +00:00
get () {
return configTarget
},
set (newConfig) {
2020-10-26 14:15:54 +00:00
if (newConfig == null) {
2020-10-25 13:04:28 +00:00
return
}
2020-10-26 17:12:40 +00:00
const merged = lodash.cloneDeep(newConfig)
2020-10-24 13:22:44 +00:00
const clone = lodash.cloneDeep(defConfig)
2020-10-26 17:12:40 +00:00
lodash.merge(merged, clone)
lodash.merge(merged, newConfig)
2020-10-25 13:04:28 +00:00
2020-11-06 10:59:54 +00:00
_deleteDisabledItem(merged)
2020-10-26 17:12:40 +00:00
configTarget = merged
2020-10-24 13:22:44 +00:00
return configTarget
},
getDefault () {
2020-10-26 17:12:40 +00:00
return lodash.cloneDeep(defConfig)
2020-10-24 13:22:44 +00:00
},
2020-10-30 09:46:45 +00:00
addDefault (key, defValue) {
lodash.set(defConfig, key, defValue)
},
2020-11-06 10:59:54 +00:00
resetDefault (key) {
if (key) {
let value = lodash.get(defConfig, key)
value = lodash.cloneDeep(value)
lodash.set(configTarget, key, value)
} else {
configTarget = lodash.cloneDeep(defConfig)
}
return configTarget
2020-10-27 13:14:12 +00:00
},
2020-10-27 17:41:04 +00:00
async getVariables (type) {
const method = type === 'npm' ? Shell.getNpmEnv : Shell.getSystemEnv
const currentMap = await method()
2020-10-27 13:14:12 +00:00
const list = []
2020-10-27 17:41:04 +00:00
const map = configTarget.variables[type]
for (const key in map) {
const exists = currentMap[key] != null
2020-10-27 13:14:12 +00:00
list.push({
key,
2020-10-27 17:41:04 +00:00
value: map[key],
2020-10-27 13:14:12 +00:00
exists
})
}
return list
},
2020-10-27 17:41:04 +00:00
async setVariables (type) {
const list = await configApi.getVariables(type)
2020-10-27 13:14:12 +00:00
const noSetList = list.filter(item => {
return !item.exists
})
if (list.length > 0) {
2020-10-29 08:14:12 +00:00
const context = {
root_ca_cert_path: configApi.get().server.setting.rootCaFile.certPath
2020-10-29 08:14:12 +00:00
}
for (const item of noSetList) {
if (item.value.indexOf('${') >= 0) {
for (const key in context) {
item.value = item.value.replcace(new RegExp('${' + key + '}', 'g'), context[key])
}
}
}
2020-10-27 17:41:04 +00:00
const method = type === 'npm' ? Shell.setNpmEnv : Shell.setSystemEnv
return method({ list: noSetList })
2020-10-27 13:14:12 +00:00
}
2020-10-24 13:22:44 +00:00
}
}
2020-10-27 13:14:12 +00:00
module.exports = configApi