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';
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);