diff options
Diffstat (limited to 'lib/process/env.ts')
-rw-r--r-- | lib/process/env.ts | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/lib/process/env.ts b/lib/process/env.ts new file mode 100644 index 0000000..f59fadf --- /dev/null +++ b/lib/process/env.ts @@ -0,0 +1,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, + ); +}; |