From 316e68518d1a8f5b8bd6d741ae3081b512b8e721 Mon Sep 17 00:00:00 2001 From: Ilyich Vismara <81801314+ilyichv@users.noreply.github.com> Date: Sat, 21 Sep 2024 23:17:47 +0200 Subject: [PATCH] feat: handle defaults (#5) --- .changeset/weak-guests-leave.md | 5 +++++ src/core/parsers.ts | 18 ++++++++++++++++++ src/utils/temp-types.ts | 1 + 3 files changed, 24 insertions(+) create mode 100644 .changeset/weak-guests-leave.md diff --git a/.changeset/weak-guests-leave.md b/.changeset/weak-guests-leave.md new file mode 100644 index 0000000..0e933f5 --- /dev/null +++ b/.changeset/weak-guests-leave.md @@ -0,0 +1,5 @@ +--- +"arke-zod": patch +--- + +feat: handle defaults diff --git a/src/core/parsers.ts b/src/core/parsers.ts index 858a2fb..0c05077 100644 --- a/src/core/parsers.ts +++ b/src/core/parsers.ts @@ -28,6 +28,7 @@ function buildSchemaString(arke: TUnit, parameters: Parameter[]) { parseType(param), parseMinMax(param), parseRequired(param), + parseDefault(param), ].join(""); return `${param.id}: ${zodStr},`; }) @@ -92,3 +93,20 @@ function parseMinMax(parameter: Parameter) { return result; } + +function parseDefault(parameter: Parameter) { + let defaultValue: string | null = parameter.default; + if ( + defaultValue !== undefined && + defaultValue !== null && + (typeof defaultValue !== "object" || Object.keys(defaultValue).length > 0) + ) { + if (parameter.type === "string") { + defaultValue = `"${defaultValue}"`; + } + + return `.default(${defaultValue})`; + } + + return ""; +} diff --git a/src/utils/temp-types.ts b/src/utils/temp-types.ts index f913059..2beba7d 100644 --- a/src/utils/temp-types.ts +++ b/src/utils/temp-types.ts @@ -15,6 +15,7 @@ export type BaseParameter = { | "boolean" | "binary"; required: boolean; + default: null; }; export type DynamicParameter = BaseParameter & {