Created
October 20, 2022 01:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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