-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRoute.ts
More file actions
38 lines (37 loc) · 1.32 KB
/
Route.ts
File metadata and controls
38 lines (37 loc) · 1.32 KB
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
import "urlpattern-polyfill"
import { http } from "cloudly-http"
import { Handler } from "./Handler"
export class Route<T> {
private constructor(
readonly pattern: URLPattern,
readonly methods: http.Method[],
private readonly handler: Handler<T>,
readonly middleware: http.Middleware
) {}
async handle(request: http.Request, context: T): Promise<http.Response | any> {
return this.middleware(request, async request => http.Response.create(await this.handler(request, context)))
}
match(request: http.Request, ...alternatePrefix: string[]): http.Request | undefined {
let path = request.url.pathname
if (path.endsWith("/"))
path = path.substring(0, path.length - 1)
const prefix = alternatePrefix.find(prefix => path.startsWith(prefix))
if (prefix)
path = path.substring(prefix.length)
const match = this.pattern.exec({ pathname: path })
return (match && { ...request, parameter: match?.pathname.groups || {} }) || undefined
}
static create<T>(
method: http.Method | http.Method[],
pattern: URLPattern | string,
handler: Handler<T>,
middleware: http.Middleware | undefined
): Route<T> {
return new Route(
typeof pattern == "string" ? new URLPattern({ pathname: pattern }) : pattern,
Array.isArray(method) ? method : [method],
handler,
middleware ?? http.Middleware.create("server")
)
}
}