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

Aborting requests with expired tokens from the Authentication Middleware #1985

Open
1 task done
darkbasic opened this issue Nov 5, 2024 · 1 comment
Open
1 task done
Labels
enhancement New feature or request openapi-fetch Relevant to the openapi-fetch library

Comments

@darkbasic
Copy link

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

@darkbasic darkbasic added enhancement New feature or request openapi-fetch Relevant to the openapi-fetch library labels Nov 5, 2024
@gzm0
Copy link
Contributor

gzm0 commented Nov 6, 2024

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:

for (const m of middlewares) {
if (m && typeof m === "object" && typeof m.onRequest === "function") {
const result = await m.onRequest({
request,
schemaPath,
params,
options,
id,
});
if (result) {
if (!(result instanceof CustomRequest)) {
throw new Error("onRequest: must return new Request() when modifying the request");
}
request = result;
}
}
}
}
// fetch!
let response = await fetch(request);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request openapi-fetch Relevant to the openapi-fetch library
Projects
None yet
Development

No branches or pull requests

2 participants