forked from utily/cloudly-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoute.ts
More file actions
22 lines (21 loc) · 747 Bytes
/
Route.ts
File metadata and controls
22 lines (21 loc) · 747 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import * as http from "cloud-http"
import { Handler } from "./Handler"
export class Route {
private constructor(readonly expression: RegExp, readonly methods: http.Method[], readonly handler: Handler) {}
match(request: http.Request): http.Request | undefined {
const match = request.url.pathname.match(this.expression)
return (match && { ...request, parameter: match.groups || {} }) || undefined
}
static create(method: http.Method | http.Method[], pattern: string, handler: Handler): Route {
return new Route(
new RegExp(
pattern
.split("/")
.map(folder => (folder.startsWith(":") ? `(?<${folder.substr(1)}>[^/\\?#]*)` : folder))
.join("/")
),
Array.isArray(method) ? method : [method],
handler
)
}
}