-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathgetEnv.ts
56 lines (53 loc) · 1.46 KB
/
getEnv.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
interface GetEnvArgs<
R extends string,
O extends Record<string, string | undefined>
> {
/**
A list of environment variables that are required.
If any of these are missing, an error will be thrown.
*/
required?: readonly R[];
/**
An object of environment variables that are optional.
If any of these are missing, they will default to the value provided.
*/
optional?: O;
}
// Helper type to determine the type of an optional env var based on its default value
type OptionalEnvType<T extends string | undefined> = T extends undefined
? string | undefined
: string;
type EnvFromArgs<
R extends string,
O extends Record<string, string | undefined>
> = {
[K in R]: string;
} & {
[K in keyof O]: OptionalEnvType<O[K]>;
};
export function getEnv<
R extends string = never,
O extends Record<string, string | undefined> = Record<never, never>
>({ required, optional }: GetEnvArgs<R, O>): EnvFromArgs<R, O> {
const env = { ...optional };
const missingRequired: string[] = [];
if (required) {
required.forEach((key) => {
env[key] = process.env[key];
if (!env[key]) {
missingRequired.push(key);
}
});
}
if (missingRequired.length > 0) {
throw new Error(
`Missing required environment variables:\n${missingRequired
.map((r) => ` - ${r}`)
.join("\n")}`
);
}
for (const key in optional) {
env[key] = process.env[key] ?? optional[key];
}
return env as EnvFromArgs<R, O>;
}