From 669ab941301c89eab72a1ec4cef8ee57db69d023 Mon Sep 17 00:00:00 2001 From: Yusuke Wada Date: Thu, 27 Jun 2024 17:45:32 +0900 Subject: [PATCH] fix(timing): prevent duplicate applications (#3054) --- src/middleware/timing/index.test.ts | 16 ++++++++++++++++ src/middleware/timing/timing.ts | 5 +++++ 2 files changed, 21 insertions(+) diff --git a/src/middleware/timing/index.test.ts b/src/middleware/timing/index.test.ts index ae5eed34f..527e73406 100644 --- a/src/middleware/timing/index.test.ts +++ b/src/middleware/timing/index.test.ts @@ -29,6 +29,12 @@ describe('Server-Timing API', () => { return c.text('cache!') }) + const sub = new Hono() + + sub.use(timing()) + sub.get('/', (c) => c.text('sub')) + app.route('/sub', sub) + it('Should contain total duration', async () => { const res = await app.request('http://localhost/') expect(res).not.toBeNull() @@ -56,6 +62,16 @@ describe('Server-Timing API', () => { expect(res.headers.get('server-timing')?.includes(regionDesc)).toBeTruthy() }) + it('Should not be enabled if the main app has the timing middleware', async () => { + const consoleWarnSpy = vi.spyOn(console, 'warn') + const res = await app.request('/sub') + expect(res.status).toBe(200) + expect(res.headers.has('server-timing')).toBeTruthy() + expect(res.headers.get('server-timing')?.includes(totalDescription)).toBeTruthy() + expect(consoleWarnSpy).not.toHaveBeenCalled() + consoleWarnSpy.mockRestore() + }) + describe('Should handle crossOrigin setting', async () => { it('Should do nothing when crossOrigin is falsy', async () => { const crossOriginApp = new Hono() diff --git a/src/middleware/timing/timing.ts b/src/middleware/timing/timing.ts index 5c76e826d..a221e8452 100644 --- a/src/middleware/timing/timing.ts +++ b/src/middleware/timing/timing.ts @@ -87,6 +87,11 @@ export const timing = (config?: TimingOptions): MiddlewareHandler => { return async function timing(c, next) { const headers: string[] = [] const timers = new Map() + + if (c.get('metric')) { + return await next() + } + c.set('metric', { headers, timers }) if (options.total) {