Skip to content

Commit cb3bafe

Browse files
authored
fix(router): make router handler non preemtive by default (#194)
1 parent b986629 commit cb3bafe

File tree

3 files changed

+31
-8
lines changed

3 files changed

+31
-8
lines changed

src/app.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,10 @@ export function createAppEventHandler (stack: Stack, options: AppOptions) {
114114
}
115115
}
116116
if (!event.res.writableEnded) {
117-
throw createError({ statusCode: 404, statusMessage: 'Not Found' })
117+
throw createError({
118+
statusCode: 404,
119+
statusMessage: `Cannot find any route matching ${event.req.url || '/'}.`
120+
})
118121
}
119122
})
120123
}

src/router.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ interface RouteNode {
1919
handlers: Partial<Record<RouterMethod | 'all', EventHandler>>
2020
}
2121

22-
export function createRouter (): Router {
22+
export interface CreateRouterOptions {
23+
preemtive?: boolean
24+
}
25+
26+
export function createRouter (opts: CreateRouterOptions = {}): Router {
2327
const _router = _createRouter<RouteNode>({})
2428
const routes: Record<string, RouteNode> = {}
2529

@@ -57,13 +61,16 @@ export function createRouter (): Router {
5761
}
5862

5963
const matched = _router.lookup(path)
60-
6164
if (!matched) {
62-
throw createError({
63-
statusCode: 404,
64-
name: 'Not Found',
65-
statusMessage: `Cannot find any route matching ${event.req.url || '/'}.`
66-
})
65+
if (opts.preemtive) {
66+
throw createError({
67+
statusCode: 404,
68+
name: 'Not Found',
69+
statusMessage: `Cannot find any route matching ${event.req.url || '/'}.`
70+
})
71+
} else {
72+
return // Let app match other handlers
73+
}
6774
}
6875

6976
// Match method

test/router.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,19 @@ describe('router', () => {
2525
expect(res.text).toEqual('Hello')
2626
})
2727

28+
it('Multiple Routers', async () => {
29+
const secondRouter = createRouter()
30+
.add('/router2', eventHandler(() => 'router2'))
31+
32+
app.use(secondRouter)
33+
34+
const res1 = await request.get('/')
35+
expect(res1.text).toEqual('Hello')
36+
37+
const res2 = await request.get('/router2')
38+
expect(res2.text).toEqual('router2')
39+
})
40+
2841
it('Handle different methods', async () => {
2942
const res1 = await request.get('/test')
3043
expect(res1.text).toEqual('Test (GET)')

0 commit comments

Comments
 (0)