Validate and transform json at the same time
This commit is contained in:
parent
d365ea26dc
commit
d8e0a1c7fc
|
@ -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);
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue