-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (59 loc) · 1.6 KB
/
Copy pathindex.js
File metadata and controls
73 lines (59 loc) · 1.6 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
64
65
66
67
68
69
70
71
72
73
const { isPlainObject } = require('is-plain-object')
let cacheEnvironment = true
let storedEnvironment = null
let detector = () => {
// detects if app is running in SSR or not (process.browser is used by webpack, browserify, next.js, ...)
if ('browser' in process) {
return !process.browser
}
// detects if it's being executed in docker
if ('platform' in process) {
return true
}
return null
}
const setDetector = (fn, cacheResult = true) => {
detector = fn
cacheEnvironment = cacheResult
storedEnvironment = null
}
const forceEnvironment = (value) => {
cacheEnvironment = true
storedEnvironment = value
}
const detectEnvironment = () => (storedEnvironment = detector())
const env = (primary, secondary) => {
const environment =
cacheEnvironment && storedEnvironment !== null ? storedEnvironment : detectEnvironment()
if (environment === null) {
throw new Error('impossible to detect environment')
}
let value
if (isPlainObject(primary)) {
value = primary[environment]
} else {
value = environment && secondary !== undefined ? secondary : primary
}
if (value === undefined) {
throw new Error(`required variable could not be found`)
}
return value instanceof Function ? value() : value
}
const wrapper = (obj) => {
try {
return new Proxy(obj, {
get: (target, name) =>
typeof target[name] === 'function' ? target[name]() : target[name] && wrapper(target[name]),
})
} catch (e) {
return obj
}
}
module.exports = {
__esModule: true,
default: wrapper,
env,
setDetector,
forceEnvironment,
detectEnvironment,
}