Skip to content

request and response transformations #476

@binaryartifex

Description

@binaryartifex

Describe the feature

useQuery and useAsyncData have the transform property enabling users to integrate data parsing into the request pipeline. if its one thing that i sadly never see done, its parsing of network responses prior to their use. having a way to provide custom parsing/transformation logic would be great to abstract away implementation details (especially for those creating custom fetches or using repository patterns). an example of such an api that i believe would not create any breaking changes...

transform could be an optional callback (the default of which is just the result of the parseResponse property). the onResponse transform can be used to ultimately infer the success type of the fetch. onRequest transform can be used for form validation logic with the respective responseError properties able to be typeguarded to a particular error type and map the errors accordingly. (ie. if onRequest transform fails, within onRequestError, determine if error type is a ZodError then map the ZodError into a format compatible with VeeValidate's form error format to return back to the ui). Injecting error states into the request/response error callbacks i feel would make the DX all the more better and include the entire data-access problem domain encapsulated to the fetch handler itself without exposing those details to components.

  const response = $fetch(url, {
    onRequest({transform}){
      transform((body) => SomeZodSchema.parse(body))
    },
    onResponse({transform}){
      transform((data) => AnotherZodSchema.parse(body)) // infer return type from this transform
    },
    onRequestError(ctx){
      console.log(ctx.error) // failed onRequest transform output (ZodError)
    },
    onResponseError(ctx){
      console.log(ctx.response._data) // failed onResponse transform output (ZodError)
    },
  })

or alternatively something like

  const response = $fetch(url, {
    transform: {
      request: (body) => SomeZodSchema.parse(body),
      response: (data) => AnotherZodSchema.parse(data) // infer return type from this transform
    },
    onRequestError(ctx){
      console.log(ctx.error) // failed transform.request output (ZodError)
    },
    onResponseError(ctx){
      console.log(ctx.response._data) // failed transform.response output (ZodError)
    },
  })

Additional information

  • Would you be willing to help implement this feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions