-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrt_test.ts
76 lines (65 loc) · 1.88 KB
/
rt_test.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
import { assertEquals } from "@std/assert";
import { createRouter } from "./rt.ts";
const router = createRouter()
.get(
"/",
({ url }) =>
new Response(`Hello, ${url.searchParams.get("name") ?? "World"}!`),
)
.default(() => new Response("Not found", { status: 404 }));
Deno.test("createRouter handles GET request", async () => {
const response = await router.fetch(
new Request("http://localhost/?name=Deno"),
);
assertEquals(await response.text(), "Hello, Deno!");
});
Deno.test("createRouter navigates unmatched route to default handler", async () => {
const response = await router.fetch(
new Request("http://localhost/404"),
);
assertEquals(response.status, 404);
});
const statefulRouter = createRouter(
(r) =>
r
.get(
"/*",
async (ctx) => {
ctx.state.user = { name: "Alice" };
return await ctx.next();
},
)
.get<"name">(
"/:name",
(ctx) => {
if (ctx.state.user === null) {
return new Response("Unauthorized", { status: 401 });
}
if (ctx.state.user.name !== ctx.params.name) {
return new Response("Forbidden", { status: 403 });
}
return new Response(`Hello, ${ctx.params.name}!`);
},
),
(): { user: User | null } => ({ user: null }),
);
interface User {
name: string;
}
Deno.test("createRouter preserves state", async () => {
const response = await statefulRouter.fetch(
new Request("http://localhost/Alice"),
);
assertEquals(await response.text(), "Hello, Alice!");
});
const nestedRouter = createRouter()
.get(
"/*",
(ctx) => statefulRouter.fetch(ctx.request),
);
Deno.test("createRouter nests routers", async () => {
const response = await nestedRouter.fetch(
new Request("http://localhost/Alice"),
);
assertEquals(await response.text(), "Hello, Alice!");
});