Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d066b0c

Browse files
committed
refactor!: function handler only
1 parent acc94e0 commit d066b0c

File tree

4 files changed

+11
-10
lines changed

4 files changed

+11
-10
lines changed

β€Žsrc/core/app.tsβ€Ž

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { handle } from './handle'
55
import { Router } from './router'
66

77
export class App {
8-
fallback: Handler = status(404)
8+
fallback?: Handler
99
layers: Layer[] = []
1010
routes: Map<string, Handler> = new Map()
1111

@@ -26,7 +26,7 @@ export class App {
2626
const result = router.find(new URL(req.url).pathname)
2727

2828
const next = async () => handle(
29-
result?.value ?? this.fallback,
29+
result?.value ?? this.fallback ?? (() => status(404)),
3030
req,
3131
result?.params,
3232
)
@@ -51,7 +51,12 @@ export class App {
5151
app.routes.forEach((handler, path) => this.routes.set(path, handler))
5252
app.layers.forEach(layer => this.layers.push(layer))
5353

54-
// TODO: merge fallback
54+
if (app.fallback) {
55+
if (!this.fallback)
56+
this.fallback = app.fallback
57+
else
58+
throw new Error('lemmih: Cannot merge two `App`s that both have a fallback')
59+
}
5560

5661
return this
5762
}

β€Žsrc/core/handle.tsβ€Ž

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import type { Handler } from '../types'
22

33
export const handle = async (handler: Handler, req: Request, params?: Record<string, string>) =>
4-
typeof handler === 'function'
5-
? handler(req, params)
6-
: handler
4+
handler(req, params)

β€Žsrc/routing/index.tsβ€Ž

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@ const routing = (method: string) =>
66
(handler: Handler): Handler =>
77
async (req, params) =>
88
req.method.toUpperCase() === method
9-
? typeof handler === 'function'
10-
? handler(req, params)
11-
: handler
9+
? handler(req, params)
1210
: status(405)
1311

1412
export const connect = routing('CONNECT')

β€Žsrc/types.tsβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export type Handler = ((req: Request, params?: Record<string, string>) => MaybePromise<Response>) | MaybePromise<Response>
1+
export type Handler = (req: Request, params?: Record<string, string>) => MaybePromise<Response>
22

33
export type Layer = (req: Request, next: Next) => MaybePromise<Response>
44

0 commit comments

Comments
Β (0)