elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.79k stars 96 forks source link

Performance API #129

Closed xpuu closed 2 years ago

xpuu commented 2 years ago

Hi Julien, do you think there might be a way to simplify and unify Performance API usage between Node.js and browser? I'm using wretch with SvelteKit. It runs fetch on both backend and frontend. To make things simple I'd like to use the same configuration for both, with the option to log slow requests. Thanks for your opinion.

elbywan commented 2 years ago

Hey @xpuu 👋,

Hi Julien, do you think there might be a way to simplify and unify Performance API usage between Node.js and browser?

Well on the wretch side it is only a matter of adding the proper polyfill for nodejs, using the performance api is done the same way for both environments by calling .perfs().

// Node.js 8.5+ only:
const { performance, PerformanceObserver } = require("perf_hooks");

wretch().polyfills({
  fetch: function (url, opts) {
    performance.mark(url + " - begin");
    return fetch(url, opts).then(res => {
      performance.mark(url + " - end");
      setTimeout(() => performance.measure(res.url, url + " - begin", url + " - end"), 0);
      return res;
    });
  },
  /* other polyfills ... */
  performance: performance,
  PerformanceObserver: PerformanceObserver,
});

// Same for Node.js and browsers:
wretch("...")
  .get()
  .perfs((timings) => {
    /* timings is platform dependent, but both node.js and the browsers populate the `startTime` and `duration` properties */
    console.log(timings.startTime);
  })
  .res();

If you are asking about the PerformanceEntry timings object itself that is retrieved in the .perfs(timings => …) callback, then I think that it is unfortunately impossible to harmonize since it is really specific to the platform.