summaryrefslogtreecommitdiff
path: root/u/process/env.ts
blob: 76961c9e34da21256795c2f9afc00e1462e17bda (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
28
29
30
31
32
33
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]).filter((val) => val.trim() !== '');

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

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: ReadonlyArray<V>) =>
    vars
        .map((envVar) => [envVar, getRequiredEnv(envVar)] as [V, IEither<Error, V>])
        .reduce(
            (acc: IEither<Error, ObjectFromList<typeof vars>>, x: [V, IEither<Error, V>]) => {
                const [envVar, eitherVal] = x;
                return acc.flatMap((args) => {
                    return eitherVal.mapRight(
                        (envValue) =>
                            ({
                                ...args,
                                [envVar]: envValue,
                            }) as ObjectFromList<typeof vars>,
                    );
                });
            },
            Either.right({} as ObjectFromList<typeof vars>),
        );