summaryrefslogtreecommitdiff
path: root/u/process/env.ts
blob: 88fb4904acbbd34016906b1c9b407e8d73f3921c (plain)
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
import { IOptional, Either, Optional, type IEither } from '@emprespresso/pengueno';

export const getEnv = <V extends string>(name: string): IOptional<V> => Optional.from(<V>process.env[name]);

export const getRequiredEnv = <V extends string>(name: string): IEither<Error, V> =>
    Either.fromFailable(() => getEnv<V>(name).get()).mapLeft(
        () => new Error(`environment variable "${name}" is required D:`),
    );

type ObjectFromList<T extends ReadonlyArray<string>, V = string> = {
    [K in T extends ReadonlyArray<infer U> ? U : never]: V;
};

export const getRequiredEnvVars = <V extends string>(vars: Array<V>) => {
    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 Either.joinRight<V, Error, Environment>(
        vars,
        (envVar: V, environment: Environment) => getRequiredEnv(envVar).mapRight(addTo(environment, envVar)),
        emptyEnvironment,
    );
};