-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconfig.js
More file actions
63 lines (49 loc) · 1.63 KB
/
config.js
File metadata and controls
63 lines (49 loc) · 1.63 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
import fs from 'node:fs/promises'
import fsSync from 'node:fs'
import YAML from 'yaml'
import { setEnv } from './util.js'
setEnv()
class Config {
constructor(opts = {}) {
this.cfg = {}
this.getEnv(opts)
}
getEnv(opts = {}) {
this.env = process.env.NODE_ENV ?? opts.env ?? ''
this.debug = Boolean(process.env.NODE_DEBUG)
if (this.debug) console.log(`debug: true, env: ${this.env}`)
}
async get(name, env) {
this.getEnv()
const cacheKey = [name, env ?? this.env].join(':')
if (this.cfg?.[cacheKey]) return this.cfg[cacheKey] // cached
const str = await fs.readFile(`./conf.d/${name}.yml`, 'utf8')
const cfg = YAML.parse(str)
if (this.debug) console.debug(cfg)
this.cfg[cacheKey] = applyDefaults(cfg[env ?? this.env], cfg.default)
return this.cfg[cacheKey]
}
getSync(name, env) {
this.getEnv()
const cacheKey = [name, env ?? this.env].join(':')
if (this.cfg?.[cacheKey]) return this.cfg[cacheKey] // cached
const str = fsSync.readFileSync(`./conf.d/${name}.yml`, 'utf8')
const cfg = YAML.parse(str)
if (this.debug) console.debug(cfg)
this.cfg[cacheKey] = applyDefaults(cfg[env ?? this.env], cfg.default)
return this.cfg[cacheKey]
}
}
function applyDefaults(cfg = {}, defaults = {}) {
for (const d in defaults) {
/* c8 ignore next */
if (d === '__proto__' || d === 'constructor') continue
if ([undefined, null].includes(cfg[d])) {
cfg[d] = defaults[d]
} else if (typeof cfg[d] === 'object' && typeof defaults[d] === 'object') {
cfg[d] = applyDefaults(cfg[d], defaults[d])
}
}
return cfg
}
export default new Config()