-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.ts
57 lines (48 loc) · 1.61 KB
/
router.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
import type { Context } from "./context.ts";
import type { PathVars, RouteString } from "./parser.ts";
import type { Handler } from "./handler.ts";
import type { AnyRoute } from "./route.ts";
import * as A from "fun/array";
import { isSome } from "fun/option";
import { pipe } from "fun/fn";
import { evaluate, puts } from "./handler.ts";
import { routeParser } from "./parser.ts";
import { route } from "./route.ts";
import { context } from "./context.ts";
export type Router<S = never> = readonly AnyRoute<S>[];
export function router<S>(): Router<S> {
return [];
}
export function append<S>(
route: AnyRoute<S>,
): (router: Router<S>) => Router<S> {
return A.append(route);
}
export function handle<R extends RouteString, S, O>(
routeString: R,
handler: Handler<Context<S, PathVars<R>>, Response, O>,
): (router: Router<S>) => Router<S> {
const parser = routeParser(routeString);
return append(route(routeString, parser, handler));
}
export function respond<R extends RouteString, S>(
routeString: R,
handler: (ctx: Context<S, PathVars<R>>) => Response | Promise<Response>,
): (router: Router<S>) => Router<S> {
return handle(routeString, puts(handler));
}
export const NotFound: Response = new Response("Not Found", { status: 404 });
export function withState<S>(
state: S,
): (router: Router<S>) => Deno.ServeHandler {
return (router) => (request) => {
for (const { parser, handler } of router) {
const path = parser(request);
// Found a matching route
if (isSome(path)) {
return pipe(handler, evaluate(context(request, state, path.value)));
}
}
return NotFound;
};
}