nuxt-open-fetch icon indicating copy to clipboard operation
nuxt-open-fetch copied to clipboard

Impossible to use transform option in hook

Open Oui-Dev opened this issue 2 months ago • 5 comments

Environment

Reproduction

export default defineNuxtPlugin((nuxtApp) => {
  const transformer = (obj: any) => {
    // ...
  };

  nuxtApp.hook('openFetch:onRequest', (ctx) => {
    ctx.options.transform = (response) => transformer(response);
  })
})

Describe the bug

I'm currently migrating from the basic useFetch to your awesome library.
When I try to add a global transformer directly in the hook, I get the error: Property 'transform' does not exist.
However, this option is available in useFetch.

Additional context

In fact, I'm not sure if this is a bug or the intended behavior. It would be really helpful to have support for a global transformer.
For example, in my case, the backend (Python) uses snake_case (so the OpenAPI schema too), and I’d like to automatically transform the entire response to camelCase on the frontend.

Is this currently possible, or would it make sense to add such a feature?

EDIT: I just saw this section in the openapi-ts docs https://openapi-ts.dev/advanced#embrace-snake-case-in-js.
Maybe I’ll simply switch everything from camelCase to snake_case.

Logs

Property 'transform' does not exist on type 'ResolvedFetchOptions<ResponseType, any>'.ts(2339)

Oui-Dev avatar Sep 30 '25 16:09 Oui-Dev

The reason why it doesn't work is that the hooks work on the $fetch which doesn't have a transform option like useFetch.

What you can do instead is hooking into openFetch:onResponse and modify ctx.response._data. This property isn't really well documented by ofetch. I only found it by asking ChatGPT 😆

Jak-Ch-ll avatar Oct 13 '25 18:10 Jak-Ch-ll

Oh, okay! Yes, I think that should work, but I might lose the auto-types, right?

Oui-Dev avatar Oct 13 '25 20:10 Oui-Dev

That is correct, the types from nuxt-open-fetch would still represent the untransformed keys.

But that would be the case either way, as changing the function signature of $client and $useClient from a hook isn't really possible in TypeScript, as far as I know.

A potential solution for that could be to use transform/postTransform from openapi-ts to transform the types as well.

Jak-Ch-ll avatar Oct 14 '25 13:10 Jak-Ch-ll

Yeah maybe it would do the trick, thks for your help !

However I'm not going to bother myself testing it, as I said in my first message (in the edit) I'm going to follow the openapi-ts recommendation and simply switch everything to snake_case it's a bit more work but it will simplify everything in the end 😊

Oui-Dev avatar Oct 14 '25 19:10 Oui-Dev

That is, most likely, the wisest solution 😄

Jak-Ch-ll avatar Oct 17 '25 11:10 Jak-Ch-ll

Since it's not a good practice to implement this feature. I close this as not planned.

Thks for your help !

Oui-Dev avatar Nov 18 '25 15:11 Oui-Dev