Last active
February 14, 2023 17:50
-
-
Save christophemarois/34bb913cad54ddc309197df33339fde0 to your computer and use it in GitHub Desktop.
Zod JSON Coercion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as z from 'zod' | |
function zJson <T extends z.ZodTypeAny> (schema: T) { | |
return z.string().transform((val, ctx) => { | |
try { | |
return JSON.parse(val) | |
} catch (err) { | |
ctx.addIssue({ | |
code: z.ZodIssueCode.custom, | |
message: 'Invalid JSON', | |
}) | |
return z.NEVER | |
} | |
}).pipe(schema) | |
} | |
// example | |
const env = z.object({ | |
// Should be a json string that parses to an array of string urls | |
WEBHOOK_URLS: zJson(z.array(z.string().url())) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment