Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow SafeParse to return data #3931

Open
jduhking opened this issue Dec 31, 2024 · 1 comment
Open

Allow SafeParse to return data #3931

jduhking opened this issue Dec 31, 2024 · 1 comment

Comments

@jduhking
Copy link

jduhking commented Dec 31, 2024

Our application is using zod in order to validate data and log any errors. However, because we want to error gracefully, we decide to use safeParse for validation.

We also use the intellisense provided by our IDE in order for better code documentation / clarity throughout the application, and for this we want to be able return the data field from our safe parse.

We want something like this:

      const getCustomer = async ( id : string ) => {

      return safeParseAsync(await axios.get(`api/v1/customer/${id}`))
      .then(result => {
       if (!result.success) {
       // log the error via some logging service
       }
       return result
      }).data

This example uses safeParseAsync but would also apply to safeParse.

Although, some parts of the data may fail validation, we may still want to be able to soften the blow later in the application and not disrupt the user experience.

@kockar96
Copy link

kockar96 commented Jan 3, 2025

This looks incomplete.
You must have a schema that you call . safeParseAsync.
What you are requesting already is supported you only have to structure it a bit differently
For example:
const getCustomer = async (id: string) => {
const response = await Schema.safeParseAsync(
await axios.get(api/v1/customer/${id}),
);

if (!response.success) {
throw response.error;
}
return response.data;
};

Or you can use safeParse which is better imo.
const getCustomer = async (id: string) => {
const response = await axios.get(api/v1/customer/${id});
const parsedResponse = Schema.safeParse(response.data);

if (!parsedResponse.success) {
throw parsedResponse.error;
}

return parsedResponse.data;
};

Or the best way is to just use parse that throws errors by design, so there is no need to return anything as zod will do it for you. I suggest this way of doing server validation as zod errors are quite a user friendly. :)

const getCustomer = async (id: string) => {
const response = await axios.get(api/v1/customer/${id});
return Schema.parse(response.data);
};

Take a look at this article, there is the last example listed there. :)
https://tkdodo.eu/blog/type-safe-react-query

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants