Skip to content

Commit

Permalink
fix(router): make router handler non preemtive by default (#194)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Oct 15, 2022
1 parent b986629 commit cb3bafe
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 8 deletions.
5 changes: 4 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ export function createAppEventHandler (stack: Stack, options: AppOptions) {
}
}
if (!event.res.writableEnded) {
throw createError({ statusCode: 404, statusMessage: 'Not Found' })
throw createError({
statusCode: 404,
statusMessage: `Cannot find any route matching ${event.req.url || '/'}.`
})
}
})
}
Expand Down
21 changes: 14 additions & 7 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ interface RouteNode {
handlers: Partial<Record<RouterMethod | 'all', EventHandler>>
}

export function createRouter (): Router {
export interface CreateRouterOptions {
preemtive?: boolean
}

export function createRouter (opts: CreateRouterOptions = {}): Router {
const _router = _createRouter<RouteNode>({})
const routes: Record<string, RouteNode> = {}

Expand Down Expand Up @@ -57,13 +61,16 @@ export function createRouter (): Router {
}

const matched = _router.lookup(path)

if (!matched) {
throw createError({
statusCode: 404,
name: 'Not Found',
statusMessage: `Cannot find any route matching ${event.req.url || '/'}.`
})
if (opts.preemtive) {
throw createError({
statusCode: 404,
name: 'Not Found',
statusMessage: `Cannot find any route matching ${event.req.url || '/'}.`
})
} else {
return // Let app match other handlers
}
}

// Match method
Expand Down
13 changes: 13 additions & 0 deletions test/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ describe('router', () => {
expect(res.text).toEqual('Hello')
})

it('Multiple Routers', async () => {
const secondRouter = createRouter()
.add('/router2', eventHandler(() => 'router2'))

app.use(secondRouter)

const res1 = await request.get('/')
expect(res1.text).toEqual('Hello')

const res2 = await request.get('/router2')
expect(res2.text).toEqual('router2')
})

it('Handle different methods', async () => {
const res1 = await request.get('/test')
expect(res1.text).toEqual('Test (GET)')
Expand Down

0 comments on commit cb3bafe

Please sign in to comment.