-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage.ts
More file actions
91 lines (76 loc) · 1.72 KB
/
usage.ts
File metadata and controls
91 lines (76 loc) · 1.72 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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
import { createRouter } from "./src/index.ts"
import type { Res, Req, ResolvedRoute } from "./src/types.ts"
type Article = {
slug: string
title: string
text: string
}
const articles = new Map<string, Article>()
type Result = {
status: number
body?: object
text?: string
}
// Create router with routes
const router = createRouter<Result>({
routes: [
{
path: "/articles/:slug",
handler: (res) => {
const params = res.route.params as { slug: string }
const a = articles.get(params.slug)
return { status: 200, body: a }
},
},
{
path: "/articles/new",
method: "POST",
handler: (res) => {
const data = res.req.data as Article
articles.set(data.slug, data)
return { status: 200, text: "ok" }
},
},
{
path: "*",
name: "not-found",
handler: (_res) => {
return { status: 404, text: "not found" }
},
},
],
})
// Create request
const req: Req = {
path: "/articles/new",
method: "POST",
data: {
slug: "slug-1",
title: "Article 1",
text: "Lorem ipsum dolor sit amet",
},
}
// use router to resolve route
const route = router.resolve(req)
// prepare object to pass to handler
const makeRes = <T>(req: Req, route: ResolvedRoute<T>) => {
const res: Res<T> = {
req,
route,
}
return res
}
// handle route
route.handler(makeRes(req, route))
// new request
const req2: Req = { path: "/articles/slug-1" }
const route2 = router.resolve(req2)
const result = route2.handler(makeRes(req2, route2))
const doSomethingWithResult = ({ status, body, text }: Result) => {
console.log(status, body, text)
// or appRoot.innerHTML = result
// or node res.writeHead(result.status)
// res.end(JSON.stringify(result.body))
// or do anything else
}
doSomethingWithResult(result)