UNPKG

@shopify/react-server

Version:
24 lines (21 loc) 750 B
import compose from 'koa-compose'; const MILLIS_PER_SECOND = 1000; const NANOS_PER_MILLIS = 1e6; const START_TIME_STATE_KEY = Symbol('startTime'); async function startRequestTiming(ctx, next) { ctx.state[START_TIME_STATE_KEY] = process.hrtime(); await next(); } async function middleware(ctx, next) { try { await next(); } finally { const [seconds, nanoseconds] = process.hrtime(ctx.state[START_TIME_STATE_KEY]); const ms = seconds * MILLIS_PER_SECOND + nanoseconds / NANOS_PER_MILLIS; const requestTime = Math.round(ms); const uiMetrics = `ui;request_time=${requestTime}`; ctx.set('Server-Timing', uiMetrics); } } const metricsMiddleware = compose([startRequestTiming, middleware]); export { metricsMiddleware };