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
|
import { IOptional, Either, Optional, type IEither, type ObjectFromList } from '@emprespresso/pengueno';
// type safe environment variables
export const getEnv = (name: string): IOptional<string> => Optional.from(process.env[name]);
export const getRequiredEnv = <V extends string>(name: V): IEither<Error, string> =>
Either.fromFailable(() => getEnv(name).get()).mapLeft(
() => new Error(`environment variable "${name}" is required D:`),
);
export const getRequiredEnvVars = <V extends string>(vars: Array<V>): IEither<Error, ObjectFromList<typeof vars>> => {
type Environment = ObjectFromList<typeof vars>;
const emptyEnvironment = Either.right<Error, Environment>(<Environment>{});
const addTo = (env: Environment, key: V, val: string) =>
<Environment>{
...env,
[key]: val,
};
return vars.reduce(
(environment, key) =>
environment.joinRight(getRequiredEnv(key), (value, environment) => addTo(environment, key, value)),
emptyEnvironment,
);
};
|