feat: create helper function to read env variables with type safety
Summary: Test Plan:
This commit is contained in:
19
src/libs/readEnvVariable.spec.ts
Normal file
19
src/libs/readEnvVariable.spec.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
15
src/libs/readEnvVariable.ts
Normal file
15
src/libs/readEnvVariable.ts
Normal 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];
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user