-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.ts
77 lines (65 loc) · 1.97 KB
/
example.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
// Run this program with
import { method } from "./router/method.ts";
import { literal, integer, combine, rest, path } from "./router/path.ts";
import { route } from "./router/route.ts";
import { App } from "./app.ts";
import { query } from "./router/query.ts";
import { equal } from "./base/parser.ts";
import { staticFileHandler } from "./handlers/staticFileHandler.ts";
import { join, fromFileUrl, dirname } from "https://deno.land/[email protected]/path/mod.ts";
type Context = {
framework: "Fun";
};
const context: Context = {
framework: "Fun",
};
const get = method<Context>("GET");
const apiSegment = literal("api");
const v1Segment = literal("v1");
const usersSegment = literal("users");
const userIdSegment = integer();
const userPathParser = combine([
apiSegment,
v1Segment,
usersSegment,
userIdSegment,
] as const);
// match query parameter
const queryParams = query({
role: equal("admin"),
});
const userRoutePaths = [get, path(userPathParser), queryParams] as const;
const userRoute = route<Context, typeof userRoutePaths>(userRoutePaths);
function handler(
context: Context,
[method, [api, v1, users, userId], queryParams]: [
string,
[string, string, string, number],
{ role: string }
]
) {
const body = {
method, // GET
path: [api, v1, users, userId], // ["api", "v1", "users", 100]
queryParams, // { role: 'admin' }
context,
};
return new Response(JSON.stringify(body), {
status: 200,
});
}
// server static files under specified folder
const staticSegment = literal("static");
const staticPathParser = combine([
staticSegment,
rest()
] as const);
const staticRoutePaths = [get, path(staticPathParser)] as const;
const staticRoute = route<Context, typeof staticRoutePaths>(staticRoutePaths);
const app = new App<Context>(context);
app.route(userRoute, handler);
const dirPath = dirname(fromFileUrl(import.meta.url));
app.route(staticRoute, staticFileHandler({ rootDir: join(dirPath, 'static') }));
app.run({
port: 8080,
});