Skip to content

Way to measure request time? #2116

Closed
Closed

Description

@morley92

Description

I'm looking to use middleware to measure the request time of openapi-fetch client requests - what's a good way to achieve this? The objects available in openapi-fetch middleware don't appear to include request time.

One approach I've considered is attaching the request start time to the Request object when onRequest is triggered, and then calculating the request time in the onResponse hook e.g.

const myMiddleware: Middleware = {
  async onRequest({ request }) {
    // @ts-ignore
    request.startTime = performance.now();
  },
  async onResponse({ request }) {
    const endTime = performance.now();
    // @ts-ignore
    const latency = endTime - request.startTime;
    console.log(latency);
  },
};

This requires working around the types somewhat though.

Are there any other approaches I could consider?

Proposal

N/A

Extra

Activity

  1. duncanbeevers commented on Jan 23, 2025

    @duncanbeevers
    Contributor

    You can track flight times outside of the middleware.

    I haven't tried this at run-time, but I think a simple Map may do the trick, without affecting any of the middleware signatures.

    const requestStartTimes: Map<Request, number> = new Map();
    const myMiddleware: Middleware = {
      async onRequest({ request }) {
        requestStartTimes.set(request, performance.now());
      },
      async onResponse({ request }) {
        const startTime = requestStartTimes.get(request);
        requestStartTimes.delete(request);
        const endTime = performance.now();
        const latency = endTime - startTime;
        console.log(latency);
      },
    };
  2. locked and limited conversation to collaborators on Jan 25, 2025
  3. converted this issue into a discussion #2121 on Jan 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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