Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
54 lines (48 loc) · 1.45 KB
/
Copy pathutils.ts
File metadata and controls
54 lines (48 loc) · 1.45 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
61DC
// TODO: export these
// https://github.com/unjs/nitro/tree/main/src/runtime/utils.env.ts
// TODO: improve types upstream
/* eslint-disable @typescript-eslint/no-explicit-any */
import destr from 'destr'
import { snakeCase } from 'scule'
type EnvOptions = {
env?: Record<string, any>
prefix?: string
altPrefix?: string
}
function getEnv(key: string, opts: EnvOptions) {
const env = opts.env ?? process.env
const envKey = snakeCase(key).toUpperCase()
return destr(
env[opts.prefix + envKey] ?? env[opts.altPrefix + envKey],
)
}
function _isObject(input: unknown) {
return typeof input === 'object' && !Array.isArray(input)
}
export function applyEnv(obj: Record<string, any>, opts: EnvOptions, parentKey = '') {
for (const key in obj) {
const subKey = parentKey ? `${parentKey}_${key}` : key
const envValue = getEnv(subKey, opts)
if (_isObject(obj[key])) {
// Same as before
if (_isObject(envValue)) {
obj[key] = { ...obj[key], ...(envValue as object) }
applyEnv(obj[key], opts, subKey)
}
// If envValue is undefined
// Then proceed to nested properties
else if (envValue === undefined) {
applyEnv(obj[key], opts, subKey)
}
// If envValue is a primitive other than undefined
// Then set objValue and ignore the nested properties
else {
obj[key] = envValue ?? obj[key]
}
}
else {
obj[key] = envValue ?? obj[key]
}
}
return obj
}