Skip to content

Use zod with query and mutation #3404

Answered by phryneas
User6531 asked this question in Q&A
Apr 27, 2023 · 1 comments · 11 replies
Discussion options

You must be logged in to vote

Pretty much. You could also write a baseQuery wrapper for zod - something roughly like this untested pseudocode:

const zodBaseQueryWrapper: BaseQueryEnhancer<
  unknown,
  { argumentSchema?: ZodSchema, dataSchema?: ZodSchema }
> = (baseQuery) => async (args, api, extraOptions) => {
  if (extraOptions.argumentSchema) {
    try {
      extraOptions.argumentSchema.parse(args)
    } catch (error) {
      return { error }
    }
  }
  const returnValue = baseQuery(args, api, extraOptions)
  if (extraOptions.dataSchema && 'data' in returnValue) {
    try {
      extraOptions.dataSchema.parse(returnValue.data)
    } catch (error) {
      return { error }
    }
  }
  return returnValue
}

Replies: 1 comment 11 replies

Comment options

You must be logged in to vote
11 replies
@phryneas
Comment options

Answer selected by User6531
@User6531
Comment options

@hhsl
Comment options

@User6531
Comment options

@Lantianyou
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
6 participants