Skip to content

Don't skip onResponse middleware when onRequest returns a Response object #2378

@jkjustjoshing

Description

@jkjustjoshing

Description

In #2072, the ability to prevent a network request from running was added, by returning a Response object from an onRequest middleware.

This correctly prevents the request from hitting the network, but I believe it incorrectly prevents all onResponse middleware from running. When adding middleware, you should account for any middleware that was added beforehand, but it should not need to account for any middleware added afterward.

Here's an example where the current functionality breaks. Let's say your first middleware is a wrapper

{
  onResponse: async ({ response }) => {
    const json = await response.json()
    return Response.json({ apiData: json })
  }
}

and after that you want to add a caching middleware, as described in the docs

{
  onRequest: async ({ 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();
    }
  },
  onResponse: ({ request, response }) => {
    if (response.ok) {
      const key = getCacheKey(request);
      cache.set(key, response.clone());
    }
  }
}

With the current behavior, any cached response would incorrectly be missing the apiData wrapper.

Proposal

If onRequest returns a Response object, any following onRequest middleware should be skipped, and there should not be any network request.

However, only onResponse middleware that was added after the middleware that returned the Response object should be skipped. Any middleware added before the aborting middleware should still run like normal.

Middleware A onRequest -----------> runs normally
    Middleware B onRequest -------> returns `Response`
        Middleware C onRequest ---> does not run
            fetch() --------------> does not run
        Middleware C onResponse --> does not run
    Middleware B onResponse ------> SHOULD RUN BUT CURRENTLY DOES NOT
Middleware A onResponse ----------> SHOULD RUN BUT CURRENTLY DOES NOT

Extra

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestopenapi-fetchRelevant to the openapi-fetch library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions