openapi-typescript
openapi-typescript copied to clipboard
Aborting requests with expired tokens from the Authentication Middleware
Description
I want to create an Authentication interceptor that whenever the JWT token is expired aborts the requests since there is no need to to keep them alive if they're going to return 401 anyway. In order to do so I need a way to access either the AbortController or the abort() function in the MiddlewareOnRequest onRequest callback.
Proposal
Instantiate a new AbortController() and expose either the controller itself or its abort() function in the MiddlewareOnRequest onRequest callback.
const authInterceptor: Middleware = {
async onRequest({ request, controller, abort }) {
// Use either abort() or controller.abort()
}
}
Example of AbortController usage:
const controller = new AbortController()
const signal = controller.signal
fetch(urlToFetch, {
method: 'get',
signal: signal,
})
controller.abort()
Checklist
- [x] I’m willing to open a PR for this (see CONTRIBUTING.md)
Instead of executing the request and then aborting it, would it make sense to just throw in the onRequest middleware in this case?
In fact, the onRequest middleware gets executed before the fetch call:
https://github.com/openapi-ts/openapi-typescript/blob/639ec45ed9155d2bc0c3d0fbebd3bc52f90ca7eb/packages/openapi-fetch/src/index.js#L107-L127
Instead of executing the request and then aborting it, would it make sense to just throw in the onRequest middleware in this case?
@gzm0 But this would entitle that I have to try-catch every outgoing request, what if I just need to silently abort ?
Just to add a little more context: this was a feature we talked about and delayed because we were determining how people used this library. When paired with TanStack Query, e.g., it would just add overhead.
But for people who are using openapi-fetch, and only openapi-fetch, without any wrapper (as some stated), it is a useful API.
A side question I have is “would adding an AbortController to every request introduce any overhead or performance concerns?” I don’t have any reason to believe it would, especially since in most scenarios, these won’t persist, will be garbage-collected, and a client should never have more than a dozen requests going at a time or so. So I think an implementation would be safe to just create an AbortController for every request.
I like @darkbasic’s proposal for the API, and would accept a PR introducing that. Any additional concerns/details we have could be addressed in the PR 🙂
Oh and yes @gzm0 to your comment, I was interpreting this the need to silently fail without throwing an error. Expired tokens are a great case where it’s helpful to at least retry silently in the background a few times before logging the user out or displaying an error message.