Skip to content

Commit

Permalink
fix: _middleware in param routes (#185)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Jun 6, 2024
1 parent 9139576 commit b30b9b7
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
10 changes: 10 additions & 0 deletions mocks/app/routes/about/[name]/_middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createRoute } from '../../../../../src/factory'
import { createMiddleware } from 'hono/factory'

const addHeader = createMiddleware(async (c, next) => {
await next()
console.log('fooo')
c.res.headers.append('x-message', 'from middleware')
})

export default createRoute(addHeader)
8 changes: 5 additions & 3 deletions src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,11 @@ export const createApp = <E extends Env>(options: BaseServerOptions<E>): Hono<E>
}
})

const middlewareFile = Object.keys(MIDDLEWARE_FILE).find((x) =>
new RegExp(dir + '/_middleware.tsx?').test(x)
)
const middlewareFile = Object.keys(MIDDLEWARE_FILE).find((x) => {
const replacedDir = dir.replace('[', '\\[').replace(']', '\\]')
return new RegExp(replacedDir + '/_middleware.tsx?').test(x)
})

if (middlewareFile) {
const middleware = MIDDLEWARE_FILE[middlewareFile]
if (middleware.default) {
Expand Down
6 changes: 6 additions & 0 deletions test-integration/apps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,12 +268,17 @@ describe('With preserved', () => {
eager: true,
})

const MIDDLEWARE = import.meta.glob('../mocks/app/routes/**/_middleware.(tsx|ts)', {
eager: true,
})

const app = createApp({
root: '../mocks/app/routes',
ROUTES: ROUTES as any,
RENDERER: RENDERER as any,
NOT_FOUND: NOT_FOUND as any,
ERROR: ERROR as any,
MIDDLEWARE: MIDDLEWARE as any,
})

it('Should return 200 response - /', async () => {
Expand Down Expand Up @@ -304,6 +309,7 @@ describe('With preserved', () => {
it('Should return 200 response - /about/me/address', async () => {
const res = await app.request('/about/me/address')
expect(res.status).toBe(200)
expect(res.headers.get('x-message')).toBe('from middleware')
// hono/jsx escape a single quote to &#39;
expect(await res.text()).toBe(
'<!DOCTYPE html><html><head><title>me&#39;s address</title></head><body><h1>About</h1><address><b>me&#39;s address</b></address></body></html>'
Expand Down

0 comments on commit b30b9b7

Please sign in to comment.