fix: readEnvVariable throws error when variable is string

This commit is contained in:
2024-09-10 22:17:40 -04:00
parent a421fe66d9
commit 56b2677eaf
4 changed files with 53 additions and 13 deletions

View File

@@ -3,10 +3,27 @@ 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);
describe("env & variable defined", () => {
it("returns boolean", () => {
expect(
readEnvVariable<boolean>({ ENABLE_ANIFY: "false" }, "ENABLE_ANIFY"),
).toBe(false);
});
it("returns string", () => {
expect(
readEnvVariable<string>(
{ QSTASH_TOKEN: "ehf73g8gyriuvnieojwicbg83hc" },
"QSTASH_TOKEN",
),
).toBe("ehf73g8gyriuvnieojwicbg83hc");
});
it("returns number", () => {
expect(
readEnvVariable<number>({ NUM_RETRIES: "123" }, "NUM_RETRIES"),
).toBe(123);
});
});
it("env defined but variable not defined, returns default value", () => {

View File

@@ -11,5 +11,13 @@ export function readEnvVariable<T>(
env: Bindings | undefined,
envVariable: EnvVariable,
): T {
return JSON.parse(env?.[envVariable] ?? null) ?? defaultValues[envVariable];
try {
return JSON.parse(env?.[envVariable] ?? null) ?? defaultValues[envVariable];
} catch (error) {
if (error instanceof SyntaxError) {
return env![envVariable];
}
throw error;
}
}