Skip to content

Commit

Permalink
fix(timing): prevent duplicate applications (#3054)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Jun 27, 2024
1 parent 0a4621f commit 669ab94
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/middleware/timing/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
5 changes: 5 additions & 0 deletions src/middleware/timing/timing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ export const timing = (config?: TimingOptions): MiddlewareHandler => {
return async function timing(c, next) {
const headers: string[] = []
const timers = new Map<string, Timer>()

if (c.get('metric')) {
return await next()
}

c.set('metric', { headers, timers })

if (options.total) {
Expand Down

0 comments on commit 669ab94

Please sign in to comment.