43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
const evals = ['false', 'true', 'null', 'undefined']
|
|
const numberRegex = /^\d+$/
|
|
|
|
export function read(columns, defaults = {}) {
|
|
columns = [...new Set(columns.concat(Object.keys(defaults)))].sort()
|
|
|
|
const missing = []
|
|
|
|
const result = columns.reduce((result, variable) => {
|
|
/* eslint-disable-next-line n/no-process-env */
|
|
let value = process.env[variable] || defaults[variable]
|
|
|
|
if (value === undefined) {
|
|
missing.push(variable)
|
|
} else {
|
|
if (typeof value === 'string') {
|
|
if (numberRegex.test(value)) {
|
|
value = Number.parseInt(value)
|
|
} else if (evals.includes(value)) {
|
|
// eslint-disable-next-line no-eval
|
|
value = eval(value)
|
|
}
|
|
}
|
|
|
|
result[variable] = value
|
|
}
|
|
|
|
return result
|
|
}, {})
|
|
|
|
if (missing.length) {
|
|
throw new Error(`Missing required env variables: ${missing.join(', ')}`)
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
export default read(['PGDATABASE', 'PGHOST', 'PGPASSWORD', 'PGPORT', 'PGUSER'], {
|
|
PGPASSWORD: null,
|
|
PGPORT: null,
|
|
PGUSER: null,
|
|
})
|