arktypea
arktype11mo ago
IOM

Is there an equivalent of zod.safeParse() for parsing incoming JSON requests?

Most people that I know that use Zod, use it mainly to parse incoming JSON request data into a schema. After reading through the docs I couldn't find anything that's really the equivalent of these methods, but wasn't sure if I'm just blind?

Generic example:

import { z } from 'zod'

const userDto = z.object({
firstName: z.string(),
lastName: z.string(),
birthDay: z.string().optional(),
phone: z.string().optional()
});

const handler = (request) => {
const parseResult = userDto.safeParse(request?.body)
if (parseResult.error) {
//extract error fields and error messages and return the api response to the user
}

}
Was this page helpful?