Skip to content

Commit

Permalink
fix: casting boolean envs
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomas2D committed Sep 17, 2024
1 parent 5905033 commit 481c6b1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
21 changes: 21 additions & 0 deletions src/internals/env.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { parseEnv } from "@/internals/env.js";
import { z } from "zod";

describe("Parsing ENV", () => {
afterEach(() => {
vi.unstubAllEnvs();
});

it("Correctly parses a string", () => {
vi.stubEnv("LOG_LEVEL", "info");
expect(parseEnv("LOG_LEVEL", z.string().min(1))).toBe("info");
});

it("Correctly parses a boolean", () => {
vi.stubEnv("ENABLE_LOGGING", " true");
expect(parseEnv.asBoolean("ENABLE_LOGGING")).toBe(true);

vi.stubEnv("ENABLE_LOGGING", "false");
expect(parseEnv.asBoolean("ENABLE_LOGGING")).toBe(false);
});
});
3 changes: 3 additions & 0 deletions src/internals/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export function parseEnv<T>(key: string, schema: z.ZodType<T>, defaultValue?: T)
}
return result.data;
}
parseEnv.asBoolean = (key: string, fallback = false) => {
return parseEnv(key, z.string(), String(fallback)).trim().toLowerCase() === "true";
};

export function hasEnv(key: string) {
return getProp(process.env, [key]) !== undefined;
Expand Down
7 changes: 2 additions & 5 deletions src/logger/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export class Logger extends Serializable implements pinoLogger.BaseLogger {
static get defaults(): Omit<LoggerInput, "raw"> & { pretty: boolean } {
return {
name: undefined,
pretty: Boolean(parseEnv("BEE_FRAMEWORK_LOG_PRETTY", z.coerce.boolean().default(false))),
pretty: parseEnv.asBoolean("BEE_FRAMEWORK_LOG_PRETTY", false),
bindings: {},
level: parseEnv(
"BEE_FRAMEWORK_LOG_LEVEL",
Expand Down Expand Up @@ -184,10 +184,7 @@ export class Logger extends Serializable implements pinoLogger.BaseLogger {
errorKey: "error",
colorize: true,
sync: true,
singleLine: parseEnv(
"BEE_FRAMEWORK_LOG_SINGLE_LINE",
z.coerce.boolean().default(true),
),
singleLine: parseEnv.asBoolean("BEE_FRAMEWORK_LOG_SINGLE_LINE", false),
} as PrettyOptions,
},
}),
Expand Down

0 comments on commit 481c6b1

Please sign in to comment.