3rd party Zod validation
Has anyone ever validated 3rd party requests with Zod? Running into an issue where one property might be different down the line since we don't control this api. If I use
safeParse
it'll give me an error object but no validated data. Is there a way to retrieve the validated data sans the property that errored out?
Maybe I'm overthinking this?Solution:Jump to solution
you can also do like
```ts
const parse = someSchema.safeParse(apiResponse);
if (!parse.success) {...
16 Replies
if you only need some keys you can make a schema for those and
.passthrough
everything else https://github.com/colinhacks/zod#passthroughGitHub
GitHub - colinhacks/zod: TypeScript-first schema validation with st...
TypeScript-first schema validation with static type inference - GitHub - colinhacks/zod: TypeScript-first schema validation with static type inference
Yeah so we have a schema for everything we need from that 3rd party. Lets say
propA
expects a string
but we get number
from the 3rd party - will passthrough
strip it out and let us continue as usual?if
propA
is on the schema, then noYeah that's the issue
you could
coerce
The possibility that
propA
might return something we didn't actually expect
Because the other team doesn't update us
Pretty sadwell thats the entire point of zod
its meant to fail if the data doesn't match the schema
Yeah that's understandable. It was an ask by the team to continue as usual with the properties which were okay. Weird.
I'll try to convince them that if this happens we should be fixing the issue thanks! @cje
for your specific example you can do something like
you could parse partial things against partial schema etc
but ultimately the point of validation is to validate
Yeah. It was kind of a weird discussion we had. Initially I believed it had to do with extra properties in the response of the 3rd party API. And I know that Zod strips the extra properties we don't care about
But it turns out they're trying to make the function continue despite the validation error
"continue with the properties that are ok"... means don't do anything with the properties that aren't ok? or just let those things into the application and pray nothing breaks?
dont validate then lol
the latter
Solution
you can also do like
I love this actually
i set this up in a few places at work
we deal with a TON of external APIs that will just change shit without telling us
so its good to know as soon as something changes
or even sometimes the schema is based on expectations of the api that aren't completely true
can easily happen with a complex api
so it becomes an edge case detector
Yeah this isn't a bad idea actually
I don't have anything for a slack channel but that's also not a bad idea as well
Thanks for the suggestion