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

Can access to typed data in interceptors #380

Open
1 task
87xie opened this issue Mar 27, 2024 · 2 comments
Open
1 task

Can access to typed data in interceptors #380

87xie opened this issue Mar 27, 2024 · 2 comments

Comments

@87xie
Copy link

87xie commented Mar 27, 2024

Describe the feature

This feature request aims to enhance the usability of interceptors by allowing seamless access to typed data within the interceptor functions.

Expected usage:

ofetch<{ id: string; }>("/api", {
  onResponse({ response }) {
    // Auto complete working with "response._data.id"
    // or the different property name such as "response.$data.id"
  },
})

Additional information

  • Would you be willing to help implement this feature?
@87xie 87xie changed the title Can access the typed data in interceptors Can access to typed data in interceptors Mar 27, 2024
@enkot
Copy link

enkot commented Mar 28, 2024

It would be great to type the response data!
But it becomes not so clear how to type it if ofetch will support:

AFAIK the only way to type chainable functions array is to specify finite number of function overloads, how RxJS does it with pipe - https://github.com/ReactiveX/rxjs/blob/master/packages/rxjs/src/internal/util/pipe.ts
It looks ugly, but it works.

@87xie
Copy link
Author

87xie commented Mar 29, 2024

Maybe we can consider separating the different context types based on situation, for example:

interface FetchOptions<
  R extends ResponseType = ResponseType,
  T = any,
> extends Omit<RequestInit, "body"> {
  // ...
  onRequestError?(
    context: Pick<FetchContext, 'options' | 'request'> & {
      response: undefined;
      error: Error;
    }
  ): Promise<void> | void;
  onResponse?(
    context: Pick<FetchContext, 'options' | 'request'> & {
      response: MappedResponseType<R, T>;
      error: undefined;
    }
  ): Promise<void> | void;
  // ...
}

ofetch<{ id: string; }>("api", {
  onRequestError({ response, error }) {
    // the error type will be Error
    // the response type will be undefined
  },
  onResponse({ response, error }) {
    // the error type will be undefined
    // the response type will be "{ id: string; }"
  },
})

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