openapi-typescript icon indicating copy to clipboard operation
openapi-typescript copied to clipboard

onRequest: must return new Request() when modifying the request

Open WesleyYue opened this issue 1 year ago • 2 comments

Description

I get the following error occasionally in a api client with a simple auth middleware: onRequest: must return new Request() when modifying the request

The error seems to be triggered because my middleware was handed a request that fails the check here, which my code then returns from the middleware and triggers the error.

It's not clear to me what triggers this. It only happens intermittently that I am able to capture in the wild. My environment is a VSCode extension host, which is essentially a nodejs environment in electron.

Any ideas how I can further debug this?

Reproduction


export class ApiManager {
  public api: ReturnType<typeof createClient<paths>>;
  constructor(private authManager: AuthManager) {
    this.api = createClient<paths>({
      baseUrl: new URL("api", process.env.VITE_API_SERVER_URL).toString(),
    });
    this.api.use(this.authMiddleware());
  }

  private authMiddleware(): Middleware {
    return {
      onRequest: ({ request }) => {
        const accessToken = this.authManager.accessToken;

        if (!accessToken) {
          throw new Error("Failed to retrieve access token.");
        }

        request.headers.set("Authorization", `Bearer ${accessToken}`);

        try {
          // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
          if (request && !(request instanceof Request)) {
            logger.warn("Got a non-request request in middleware.", { request });
            scope.captureException(new Error("Got a non-request request in middleware."), {
              data: { request },
            });
          }
        } catch (e) {
          // Don't fail on this.
          logger.error("Error in authMiddleware", { error: e });
        }
        return request;
      },
    };
  }
}

Expected result

Middleware should receive a request that is actually a Request. It should not be handed a object that will fail the subsequent Request check without any changes.

Checklist

WesleyYue avatar Aug 13 '24 20:08 WesleyYue