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

Allow returning Response from onRequest callback #2072

Open
1 task done
paveldubovitsky opened this issue Dec 27, 2024 · 1 comment · May be fixed by #2091
Open
1 task done

Allow returning Response from onRequest callback #2072

paveldubovitsky opened this issue Dec 27, 2024 · 1 comment · May be fixed by #2091
Assignees
Labels
enhancement New feature or request openapi-fetch Relevant to the openapi-fetch library

Comments

@paveldubovitsky
Copy link

paveldubovitsky commented Dec 27, 2024

Description

Currently, middleware can only modify requests before they are sent to the server. There's no way to short-circuit the middleware chain and return a response immediately, which is useful for cases like deduplicating or caching responses to avoid unnecessary network requests.

Proposal

Allow middleware's onRequest hook to return a Response object. When a middleware returns a Response:

  • The request is not sent to the server
  • Subsequent onRequest handlers are skipped
  • onResponse handlers are skipped

Example usage:

// Simple cache middleware example
const createCacheMiddleware = (): Middleware => {
  const cache = new Map<string, Response>();
  const getCacheKey = (request: Request) => `${request.method}:${request.url}`;
  
  return {
    async onRequest({ request }) {
      const key = getCacheKey(request);
      const cached = cache.get(key);
      if (cached) {
        // Return cached response, skipping actual request and remaining middleware chain
        return cached.clone();
      }
    },
    async onResponse({ request, response }) {
      if (response.ok) {
        const key = getCacheKey(request);
        cache.set(key, response);
      }
    }
  };
};

Checklist

@paveldubovitsky paveldubovitsky added enhancement New feature or request openapi-fetch Relevant to the openapi-fetch library labels Dec 27, 2024
@drwpow drwpow self-assigned this Jan 3, 2025
@drwpow
Copy link
Contributor

drwpow commented Jan 3, 2025

Oh this is clever! To be honest, I just have never thought of this, but I can see the usefulness of this.

I think you’ve proposed a clear usecase of why someone would want this, and this API seems to be backwards-compatible enough I think we could add in without disrupting anyone. Since onRequest() doesn’t return a response currently, this wouldn’t a breaking change.

Would happily accept a PR for this following your proposal

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
Status: Accepted
2 participants