Skip to content

Instantly share code, notes, and snippets.

@jamesarosen
Created October 20, 2022 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesarosen/847b997d6fa352b2cf01e8f2bc54a343 to your computer and use it in GitHub Desktop.
Save jamesarosen/847b997d6fa352b2cf01e8f2bc54a343 to your computer and use it in GitHub Desktop.
addServerTiming is a node function that wraps a sync or async function and adds server-timing headers with the elapsed time.
/**
* @example
* const users = addServerTiming(responseHeaders, 'LU', () => db.fetch('users'))
* @see https://web.dev/custom-metrics/?utm_source=devtools#server-timing-api
*/
export default function addServerTiming<T>(headers: Headers, label: string, callback: () => T): T {
const start = Date.now();
const maybePromise = callback();
if (maybePromise instanceof Promise) {
return maybePromise.then((result) => {
const end = Date.now();
headers.set(
"Server-Timing",
[headers.get("Server-Timing"), `${label};dur=${end - start}`].filter(Boolean).join(", "),
);
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return result;
}) as T;
}
const end = Date.now();
headers.set(
"Server-Timing",
[headers.get("Server-Timing"), `${label};dur=${end - start}`].filter(Boolean).join(", "),
);
return maybePromise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment