summaryrefslogtreecommitdiff
path: root/u/process/env.ts
diff options
context:
space:
mode:
Diffstat (limited to 'u/process/env.ts')
-rw-r--r--u/process/env.ts36
1 files changed, 36 insertions, 0 deletions
diff --git a/u/process/env.ts b/u/process/env.ts
new file mode 100644
index 0000000..0e41b4f
--- /dev/null
+++ b/u/process/env.ts
@@ -0,0 +1,36 @@
+import { Either, type IEither } from "@emprespresso/pengueno";
+
+export const getRequiredEnv = <V extends string>(name: V): IEither<Error, V> =>
+ Either
+ .fromFailable<Error, V>(() => Deno.env.get(name) as V) // could throw when no permission.
+ .flatMap((v) =>
+ (v && Either.right(v)) ||
+ Either.left(
+ 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: 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>),
+ );