Validate and transform json at the same time

This commit is contained in:
Alex Gleason 2023-03-18 19:14:19 -05:00
parent d365ea26dc
commit d8e0a1c7fc
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
1 changed files with 6 additions and 8 deletions

View File

@ -1,15 +1,13 @@
import { z } from '@/deps.ts'; import { z } from '@/deps.ts';
const jsonSchema = z.string().refine((value) => { const jsonSchema = z.string().transform((value, ctx) => {
try { try {
// FIXME: this calls JSON.parse twice. Can we make it not do that? return JSON.parse(value);
// https://github.com/colinhacks/zod/discussions/2215 } catch (_e) {
JSON.parse(value); ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid JSON' });
return true; return z.NEVER;
} catch (_) {
return false;
} }
}).transform((value) => JSON.parse(value)); });
const optionalString = z.string().optional().catch(undefined); const optionalString = z.string().optional().catch(undefined);