-
-
Notifications
You must be signed in to change notification settings - Fork 445
/
hono.ts
270 lines (236 loc) · 7.91 KB
/
hono.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import { compose } from './compose.ts'
import { Context } from './context.ts'
import { extendRequestPrototype } from './request.ts'
import type { Router } from './router.ts'
import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router.ts'
import { RegExpRouter } from './router/reg-exp-router/index.ts'
import { SmartRouter } from './router/smart-router/index.ts'
import { StaticRouter } from './router/static-router/index.ts'
import { TrieRouter } from './router/trie-router/index.ts'
import type { ExecutionContext } from './types.ts'
import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types.ts'
import { getPathFromURL, mergePath } from './utils/url.ts'
interface HandlerInterface<
P extends string,
E extends Partial<Environment> = Environment,
S = unknown,
U = Hono<E, P, S>
> {
// app.get(handler...)
<Path extends string, Data = S>(
...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]
): Hono<E, Path, Data & S>
(...handlers: Handler<P, E, S>[]): U
// app.get('/', handler, handler...)
<Path extends string, Data = S>(
path: Path,
...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]
): Hono<E, Path, Data & S>
<Path extends string, Data = S>(path: Path, ...handlers: Handler<string, E, Data>[]): Hono<
E,
string,
Data & S
>
(path: string, ...handlers: Handler<P, E, S>[]): U
}
type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE
function defineDynamicClass(): {
new <
E extends Partial<Environment> = Environment,
P extends string = string,
S = unknown,
U = Hono<E, P, S>
>(): {
[K in Methods]: HandlerInterface<P, E, S, U>
}
} {
return class {} as never
}
interface Route<
P extends string = string,
E extends Partial<Environment> = Environment,
S = unknown
> {
path: string
method: string
handler: Handler<P, E, S>
}
export class Hono<
E extends Partial<Environment> = Environment,
P extends string = string,
S = unknown
> extends defineDynamicClass()<E, P, S, Hono<E, P, S>> {
readonly router: Router<Handler<P, E, S>> = new SmartRouter({
routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],
})
readonly strict: boolean = true // strict routing - default is true
private _tempPath: string = ''
private path: string = '/'
routes: Route<P, E, S>[] = []
constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {
super()
extendRequestPrototype()
const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]
allMethods.map((method) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this[method] = (args1: string | Handler, ...args: Handler[]) => {
if (typeof args1 === 'string') {
this.path = args1
} else {
this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)
}
args.map((handler) => {
if (typeof handler !== 'string') {
this.addRoute(method, this.path, handler as unknown as Handler<P, E, S>)
}
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return this as unknown as Hono<E, any, any>
}
})
Object.assign(this, init)
}
private notFoundHandler: NotFoundHandler<E> = (c: Context<string, E>) => {
return c.text('404 Not Found', 404)
}
private errorHandler: ErrorHandler<E> = (err: Error, c: Context<string, E>) => {
console.trace(err)
const message = 'Internal Server Error'
return c.text(message, 500)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
route(path: string, app?: Hono<any>) {
this._tempPath = path
if (app) {
app.routes.map((r) => {
this.addRoute(r.method, r.path, r.handler as unknown as Handler<P, E, S>)
})
this._tempPath = ''
}
return this
}
use<Path extends string = string, Data = unknown>(
...middleware: Handler<Path, E, Data>[]
): Hono<E, P, S>
use<Path extends string = string, Data = unknown>(
arg1: string,
...middleware: Handler<Path, E, Data>[]
): Hono<E, P, S>
use(arg1: string | Handler<P, E, S>, ...handlers: Handler<P, E, S>[]) {
if (typeof arg1 === 'string') {
this.path = arg1
} else {
handlers.unshift(arg1)
}
handlers.map((handler) => {
this.addRoute(METHOD_NAME_ALL, this.path, handler)
})
return this
}
on(method: string, path: string, ...handlers: Handler<P, E, S>[]) {
if (!method) return this
this.path = path
handlers.map((handler) => {
this.addRoute(method.toUpperCase(), this.path, handler)
})
return this
}
onError(handler: ErrorHandler<E>) {
this.errorHandler = handler
return this
}
notFound(handler: NotFoundHandler<E>) {
this.notFoundHandler = handler
return this
}
showRoutes() {
const length = 8
this.routes.map((route) => {
console.log(
`\x1b[32m${route.method}\x1b[0m ${' '.repeat(length - route.method.length)} ${route.path}`
)
})
}
private addRoute(method: string, path: string, handler: Handler<P, E, S>) {
method = method.toUpperCase()
if (this._tempPath) {
path = mergePath(this._tempPath, path)
}
this.router.add(method, path, handler)
const r: Route<P, E, S> = { path: path, method: method, handler: handler }
this.routes.push(r)
}
private matchRoute(method: string, path: string) {
return this.router.match(method, path)
}
private handleError(err: unknown, c: Context<string, E>) {
if (err instanceof Error) {
return this.errorHandler(err, c)
}
throw err
}
private dispatch(
request: Request,
eventOrExecutionCtx?: ExecutionContext | FetchEvent,
env?: E['Bindings']
) {
const path = getPathFromURL(request.url, this.strict)
const method = request.method
const result = this.matchRoute(method, path)
request.paramData = result?.params
const c = new Context<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)
// Do not `compose` if it has only one handler
if (result && result.handlers.length === 1) {
const handler = result.handlers[0]
let res: ReturnType<Handler<P>>
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
res = handler(c as any, async () => {})
if (!res) return this.notFoundHandler(c)
} catch (err) {
return this.handleError(err, c)
}
if (res instanceof Response) return res
return (async () => {
let awaited: Response | undefined | void
try {
awaited = await res
if (!awaited) {
return this.notFoundHandler(c)
}
} catch (err) {
return this.handleError(err, c)
}
return awaited
})()
}
const handlers = result ? result.handlers : [this.notFoundHandler]
const composed = compose<Context<P, E>, E>(handlers, this.notFoundHandler, this.errorHandler)
return (async () => {
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const tmp = composed(c as any)
const context = tmp instanceof Promise ? await tmp : tmp
if (!context.finalized) {
throw new Error(
'Context is not finalized. You may forget returning Response object or `await next()`'
)
}
return context.res
} catch (err) {
return this.handleError(err, c)
}
})()
}
handleEvent = (event: FetchEvent) => {
return this.dispatch(event.request, event)
}
fetch = (request: Request, Environment?: E['Bindings'], executionCtx?: ExecutionContext) => {
return this.dispatch(request, executionCtx, Environment)
}
request = async (input: Request | string, requestInit?: RequestInit) => {
const req = input instanceof Request ? input : new Request(input, requestInit)
return await this.fetch(req)
}
}