Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion src/middleware/timing/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Hono } from '../../hono'
import { endTime, setMetric, startTime, timing } from '.'
import { endTime, setMetric, startTime, timing, wrapTime } from '.'

describe('Server-Timing API', () => {
const app = new Hono()
Expand All @@ -23,6 +23,20 @@ describe('Server-Timing API', () => {

return c.text('api!')
})
app.get('/api-wrap', async (c) => {
await wrapTime(c, name, new Promise((r) => setTimeout(r, 30)))

return c.text('api!')
})
app.get('/api-wrap-throw', async (c) => {
try {
await wrapTime(c, name, new Promise((_, r) => setTimeout(r, 30)))
} catch (e) {
return c.text(`error :( ${e}`, 500)
}

return c.text('api!')
})
app.get('/cache', async (c) => {
setMetric(c, region, regionDesc)

Expand Down Expand Up @@ -51,6 +65,23 @@ describe('Server-Timing API', () => {
expect(res.headers.get('server-timing')?.includes(name)).toBeTruthy()
})

it('Should contain value metrics, wrapped', async () => {
const res = await app.request('http://localhost/api-wrap')
expect(res).not.toBeNull()
expect(res.headers.has('server-timing')).toBeTruthy()
expect(res.headers.get('server-timing')?.includes(`${name};dur=`)).toBeTruthy()
expect(res.headers.get('server-timing')?.includes(name)).toBeTruthy()
})

it('Should contain value metrics, wrapped throw', async () => {
const res = await app.request('http://localhost/api-wrap-throw')
expect(res).not.toBeNull()
expect(res.headers.has('server-timing')).toBeTruthy()
expect(res.status).toBeGreaterThanOrEqual(500)
expect(res.headers.get('server-timing')?.includes(`${name};dur=`)).toBeTruthy()
expect(res.headers.get('server-timing')?.includes(name)).toBeTruthy()
})

it('Should contain value-less metrics', async () => {
const res = await app.request('http://localhost/cache')
expect(res).not.toBeNull()
Expand Down
3 changes: 2 additions & 1 deletion src/middleware/timing/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { TimingVariables } from './timing'

export { TimingVariables }
export { timing, setMetric, startTime, endTime } from './timing'
export { timing, setMetric, startTime, endTime, wrapTime } from './timing'

declare module '../..' {
interface ContextVariableMap extends TimingVariables {}
Expand Down
37 changes: 37 additions & 0 deletions src/middleware/timing/timing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,40 @@ export const endTime = (c: Context, name: string, precision?: number) => {
setMetric(c, name, duration, description, precision)
metrics.timers.delete(name)
}

/**
* Wrap a Promise to capture its duration.
* @param {Context} c - The context of the request.
* @param {string} name - The name of the timer.
* @param {Promise<T>} callable - The Promise to time.
* @param {string} [description] - The description of the timer.
* @param {number} [precision] - The precision of the timer value.
*
* @example
* ```ts
* // Instead of this:
* const data = await db.findMany(...);
*
* // do this:
* const data = await wrapTime(c, 'query', db.findMany(...));
* ```
* */
export async function wrapTime<T>(
c: Context,
name: string,
callable: Promise<T>,
description?: string,
precision?: number
): Promise<T> {
startTime(c, name, description)
let result
try {
result = await callable
return result
// eslint-disable-next-line no-useless-catch
} catch (e) {
throw e
} finally {
endTime(c, name, precision)
}
}
Loading