-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathenvsafe.ts
90 lines (78 loc) · 2.11 KB
/
envsafe.ts
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { InvalidEnvError, MissingEnvError } from './errors';
import { freezeObject } from './freezeObject';
import { defaultReporter } from './reporter';
import {
EnvsafeOpts,
Environment,
Errors,
ValidatorSpec,
Validators,
} from './types';
function getValueOrThrow<TValue>({
env,
validator,
key,
}: {
env: Environment;
validator: ValidatorSpec<TValue>;
key: string;
}): TValue {
const usingDevDefault = env.NODE_ENV !== 'production';
const { allowEmpty = false } = validator;
/**
* Function to see if the value isn't empty or undefined
*/
function isSet(value: string | TValue | undefined): value is string | TValue {
if (!allowEmpty) {
return value !== undefined && value !== '';
}
return value !== undefined;
}
let input: string | TValue | undefined = isSet(validator.input)
? validator.input
: env[key];
if (usingDevDefault && !isSet(input) && isSet(validator.devDefault)) {
input = validator.devDefault;
}
if (!isSet(input) && isSet(validator.default)) {
input = validator.default;
}
if (!isSet(input)) {
let errMessage = `Missing value`;
if (!validator.allowEmpty) {
errMessage += ' or empty string';
}
throw new MissingEnvError(errMessage);
}
const output = validator._parse(input);
if (validator.choices && !validator.choices.includes(output)) {
throw new InvalidEnvError(
`Value "${output}" not in choices [${validator.choices}]`,
);
}
return output;
}
export function envsafe<TCleanEnv>(
validators: Validators<TCleanEnv>,
{
reporter = defaultReporter,
env = process.env,
strict = false,
}: EnvsafeOpts<TCleanEnv> = {},
): Readonly<TCleanEnv> {
const errors: Errors = {};
const output = {} as TCleanEnv;
for (const key in validators) {
const validator = validators[key];
try {
const resolved = getValueOrThrow({ env, validator, key });
output[key] = resolved;
} catch (err) {
errors[key] = err as Error;
}
}
if (Object.keys(errors).length) {
reporter({ errors, output, env });
}
return strict ? freezeObject(output, env) : output;
}