-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.ts
45 lines (43 loc) · 1.19 KB
/
route.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
import { compose } from "./composition.ts";
import { type Context } from "./context.ts";
export type Middleware<C extends Context> = (
ctx: C,
) => C | Promise<C>;
export type Method =
| "ALL"
| "CONNECT"
| "DELETE"
| "GET"
| "HEAD"
| "OPTIONS"
| "PATCH"
| "POST"
| "PUT"
| "TRACE";
/**
* A curried function which takes HTTP `Method`s, a `URLPatternInput` and
* `Middleware`s and returns in the end a composed route function.
* ```ts
* createRoute("GET")({ pathname: "*" })(middleware)
* ```
*/
export function createRoute(...methods: Method[]) {
return (urlPatternInput: URLPatternInput) => {
const urlPattern = new URLPattern(urlPatternInput);
return <C extends Context>(...middlewares: Middleware<C>[]) =>
async (ctx: C): Promise<C> => {
if (
methods.includes("ALL") ||
methods.includes(ctx.request.method as Method) ||
(ctx.request.method === "HEAD" && methods.includes("GET"))
) {
const urlPatternResult = urlPattern.exec(ctx.url);
if (urlPatternResult) {
ctx.result = urlPatternResult;
return await compose<C | Promise<C>>(...middlewares)(ctx);
}
}
return ctx;
};
};
}