Last active
September 19, 2023 20:53
-
-
Save jinsley8/b26a9bcb02e6c6938325df93488de8b0 to your computer and use it in GitHub Desktop.
Zod Parsing Errors
This file contains hidden or 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 { ZodTypeAny } from 'zod'; | |
/* | |
* .safeParse | |
*/ | |
interface ZodResponseSuccess<T> { | |
success: true; | |
data: T; | |
} | |
interface ZodResponseFailure { | |
success: false; | |
errors: Record<string, string>; | |
} | |
type ZodResponse<T> = ZodResponseSuccess<T> | ZodResponseFailure; | |
export function zodValidateValue<T extends ZodTypeAny>(value: unknown, schema: T): ZodResponse<T['_output']> { | |
const validationResult = schema.safeParse(value); | |
if (validationResult.success) { | |
return { success: true, data: validationResult.data }; | |
} else { | |
const errors: Record<string, string> = {}; | |
validationResult.error.issues.forEach((issue) => { | |
const path = issue.path.join('.'); | |
errors[path] = issue.message; | |
}); | |
return { success: false, errors }; | |
} | |
} | |
// On Error this would return errors in an object: | |
ZOD ERROR { | |
success: false, | |
errors: { | |
name: 'Must be at least 10 letters', | |
program: 'Required', | |
client: 'Required', | |
} | |
} | |
/* | |
* .parse | |
*/ | |
interface ZodParsedData<T> { | |
data: T; | |
} | |
interface ZodParsedError { | |
errors: Record<string, string>; | |
} | |
type ZodParsedResult<T> = ZodParsedData<T> | ZodParsedError; | |
export function zodParseValue<T extends ZodTypeAny>(value: unknown, schema: T): ZodParsedResult<T['_output']> { | |
try { | |
const data = schema.parse(value); | |
return { data }; | |
} catch (error) { | |
if (error instanceof ZodError) { | |
const errors: Record<string, string> = {}; | |
error.issues.forEach((issue) => { | |
const path = issue.path.join('.'); | |
errors[path] = issue.message; | |
}); | |
return { errors }; | |
} else { | |
throw error; | |
} | |
} | |
} | |
// On Error this would return errors in an object: | |
ZOD ERROR { | |
errors: { | |
name: 'Must be at least 10 letters', | |
program: 'Required', | |
client: 'Required', | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment