From 6fe664dff2271eaa99b70e74b316a8b6ebf4ea13 Mon Sep 17 00:00:00 2001 From: Zuri Klaschka Date: Tue, 29 Oct 2024 14:29:24 +0100 Subject: [PATCH] feat: :technologist: Allow single-argument call of `initVariable(envVariable: string)`, defaulting to the `OPTIONAL` built-in validator --- mod.ts | 4 ++-- mod_test.ts | 19 ++++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/mod.ts b/mod.ts index c95f427..a5f6f76 100644 --- a/mod.ts +++ b/mod.ts @@ -56,7 +56,7 @@ export class EnvNotSetError extends Error { * 5. Validate the environment variable's value using `validator`. * * @param envVariable name of the environment variable - * @param validator Zod schema used to validate the environment variable's value + * @param validator Zod schema used to validate the environment variable's value. Defaults to {@link OPTIONAL}. * @param defaultValue default value for the environment variable * * @throws {ConfigParseError} If the final environment variable's value cannot be parsed using `validator`, @@ -66,7 +66,7 @@ export class EnvNotSetError extends Error { */ export async function initVariable( envVariable: string, - validator: ZodSchemaCompat, + validator: ZodSchemaCompat = OPTIONAL, defaultValue?: string, ): Promise { logger().debug(`(${envVariable}) Setting up environment variable.`, { diff --git a/mod_test.ts b/mod_test.ts index 15a00cc..6cd8e57 100644 --- a/mod_test.ts +++ b/mod_test.ts @@ -296,6 +296,23 @@ Deno.test("initVariable", async (t) => { "Expected the value to be undefined", ); }); + + await t.step("Single Argument defaults to OPTIONAL", async (t) => { + prepare("XXX"); + await initVariable(ENV_VAR); + await assertEquals( + Deno.env.get(ENV_VAR), + "XXX", + "Expected the value to be undefined", + ); + prepare(); + await initVariable(ENV_VAR); + await assertEquals( + Deno.env.get(ENV_VAR), + undefined, + "Expected the value to be undefined", + ); + }); }); Deno.test("Built-in ZodSchemaCompat Validators", async (t) => { @@ -332,7 +349,7 @@ Deno.test("Built-in ZodSchemaCompat Validators", async (t) => { [ "", ], - ) + ); function testZodSchemaCompatValidator( ctx: Deno.TestContext,