From d8e0a1c7fcf07f188b70a1ec4a714fc00462b58b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sat, 18 Mar 2023 19:14:19 -0500 Subject: [PATCH] Validate and transform json at the same time --- src/schema.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/schema.ts b/src/schema.ts index 639d3909..18b0e8bf 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -1,15 +1,13 @@ import { z } from '@/deps.ts'; -const jsonSchema = z.string().refine((value) => { +const jsonSchema = z.string().transform((value, ctx) => { try { - // FIXME: this calls JSON.parse twice. Can we make it not do that? - // https://github.com/colinhacks/zod/discussions/2215 - JSON.parse(value); - return true; - } catch (_) { - return false; + return JSON.parse(value); + } catch (_e) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid JSON' }); + return z.NEVER; } -}).transform((value) => JSON.parse(value)); +}); const optionalString = z.string().optional().catch(undefined);