feat: create helper function to read env variables with type safety

Summary:

Test Plan:
This commit is contained in:
2024-05-30 09:46:42 -04:00
parent 7aab9a19ec
commit 40daf70209
2 changed files with 34 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
import { describe, expect, it } from "bun:test";
import { readEnvVariable } from "./readEnvVariable";
describe("readEnvVariable", () => {
it("env & variable defined, returns env value", () => {
expect(
readEnvVariable<boolean>({ ENABLE_ANIFY: "false" }, "ENABLE_ANIFY"),
).toBe(false);
});
it("env defined but variable not defined, returns default value", () => {
expect(readEnvVariable<boolean>({ FOO: "bar" }, "ENABLE_ANIFY")).toBe(true);
});
it("env not defined, returns default value", () => {
expect(readEnvVariable<boolean>(undefined, "ENABLE_ANIFY")).toBe(true);
});
});

View File

@@ -0,0 +1,15 @@
import type { Bindings } from "hono/types";
import type { Env } from "~/types/env";
type EnvVariable = keyof Omit<Env, "Bindings" | "Variables">;
const defaultValues: Record<EnvVariable, any> = {
ENABLE_ANIFY: true,
};
export function readEnvVariable<T>(
env: Bindings | undefined,
envVariable: EnvVariable,
): T {
return JSON.parse(env?.[envVariable] ?? null) ?? defaultValues[envVariable];
}