From b9e34ba1c479404fb3dfac8aec6131e16c15dbe0 Mon Sep 17 00:00:00 2001 From: golebiowskib Date: Tue, 16 May 2023 14:32:13 +0200 Subject: [PATCH] feature: add extracgin options from z.array(z.enum([]) and z.enum([]).array() via useEnumValues hook --- package.json | 1 + .../getMetaInformationForZodType.test.ts | 21 +++++++++++++++++++ src/getMetaInformationForZodType.ts | 3 ++- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index a28a841..45dabae 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "dev": "jest --watchAll", "test:cov": "jest --coverage", "test": "jest", + "watch": "jest --watch", "build": "npx rollup -c rollup.config.js", "build-test:dryrun": "act -j build-test -P ubuntu-latest=ghcr.io/catthehacker/ubuntu:js-latest", "pretty": "prettier --write \"./**/*.{js,jsx,ts,tsx,json}\"" diff --git a/src/__tests__/getMetaInformationForZodType.test.ts b/src/__tests__/getMetaInformationForZodType.test.ts index c667d97..7ff8b0d 100644 --- a/src/__tests__/getMetaInformationForZodType.test.ts +++ b/src/__tests__/getMetaInformationForZodType.test.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { + getEnumValues, getMetaInformationForZodType, SPLIT_DESCRIPTION_SYMBOL, } from "../getMetaInformationForZodType"; @@ -58,4 +59,24 @@ describe("getMetaInformationForZodType", () => { placeholder: undefined, }); }); + + it("should get the enum values if the schema is an enum", () => { + const result = getEnumValues(z.enum(["a", "b", "c"])); + expect(result).toStrictEqual(["a", "b", "c"]); + }) + + it("should get the enum values if the schema is an array of enums", () => { + const result = getEnumValues(z.array(z.enum(["a", "b", "c"]))); + expect(result).toStrictEqual(["a", "b", "c"]); + }) + + it("should get the enum values if the schema is an array of enums 2", () => { + const result = getEnumValues(z.enum(["a", "b", "c"]).array()); + expect(result).toStrictEqual(["a", "b", "c"]); + }) + + it("should return undefined if the schema is not an enum", () => { + const result = getEnumValues(z.string()); + expect(result).toBeUndefined(); + }) }); diff --git a/src/getMetaInformationForZodType.ts b/src/getMetaInformationForZodType.ts index 2ae5538..6b964a7 100644 --- a/src/getMetaInformationForZodType.ts +++ b/src/getMetaInformationForZodType.ts @@ -16,7 +16,8 @@ export function parseDescription(description?: string) { }; } -export function getEnumValues(type: RTFSupportedZodTypes) { +export function getEnumValues(type: RTFSupportedZodTypes): readonly string[] | undefined { + if (type._def.typeName === z.ZodFirstPartyTypeKind.ZodArray) return getEnumValues(type._def.type) if (!(type._def.typeName === z.ZodFirstPartyTypeKind.ZodEnum)) return; return type._def.values as readonly string[]; }