Repository navigation
Expand file tree
/
Copy pathdemo.ts
More file actions
221 lines (191 loc) · 5.5 KB
/
Copy pathdemo.ts
File metadata and controls
221 lines (191 loc) · 5.5 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { once } from "node:events";
import { isDeepStrictEqual, styleText } from "node:util";
import { createExpressApp } from "./express/app.js";
import { createFastifyApp } from "./fastify/app.js";
type Case = {
label: string;
method: "GET" | "POST";
path: string;
body?: string;
status: number;
code?: string;
};
const ANA = '{"email":"ana@example.com","name":"Ana"}';
const BOOM: Case = {
label: "GET /boom",
method: "GET",
path: "/boom",
status: 500,
code: "Http.unexpected",
};
// In order: case 2 needs the user from case 1, case 3 reads it back.
const CASES: Case[] = [
{
label: "POST /users",
method: "POST",
path: "/users",
body: ANA,
status: 201,
},
{
label: "POST /users (again)",
method: "POST",
path: "/users",
// Another case, the same email: Email normalizes it before the check.
body: '{"email":"ANA@example.com","name":"Ana"}',
status: 409,
code: "User.emailTaken",
},
{ label: "GET /users/1", method: "GET", path: "/users/1", status: 200 },
{
label: "GET /users/999",
method: "GET",
path: "/users/999",
status: 404,
code: "User.notFound",
},
{
label: "POST /users (bad JSON)",
method: "POST",
path: "/users",
body: '{"email":',
status: 400,
code: "Http.malformedJson",
},
{
label: "POST /users (no name)",
method: "POST",
path: "/users",
body: '{"email":"ben@example.com"}',
status: 422,
code: "Validation.invalidBody",
},
{
label: "POST /users (blank name)",
method: "POST",
path: "/users",
body: '{"email":"ben@example.com","name":" "}',
status: 422,
code: "User.invalidName",
},
{
label: "POST /users (bad email)",
method: "POST",
path: "/users",
body: '{"email":"nope","name":"Ben"}',
status: 422,
code: "User.invalidEmail",
},
BOOM,
{
label: "GET /nope",
method: "GET",
path: "/nope",
status: 404,
code: "Http.routeNotFound",
},
];
const LABEL_WIDTH = 24;
type Answer = { status: number; body: unknown };
async function send(baseUrl: string, c: Case): Promise<Answer> {
const response = await fetch(new URL(c.path, baseUrl), {
method: c.method,
...(c.body === undefined
? {}
: { headers: { "content-type": "application/json" }, body: c.body }),
});
const body: unknown = await response.json();
return { status: response.status, body };
}
// The request id is random by design, so it is left out of the comparison.
function withoutRequestId(body: unknown): unknown {
if (typeof body !== "object" || body === null || !("requestId" in body)) {
return body;
}
const { requestId: _requestId, ...rest } = body;
return rest;
}
function codeOf(body: unknown): string | undefined {
if (
typeof body === "object" &&
body !== null &&
"code" in body &&
typeof body.code === "string"
) {
return body.code;
}
return undefined;
}
function statusCell(answer: Answer, expected: number): string {
const passed = answer.status === expected;
const mark = passed ? styleText("green", "✓") : styleText("red", "✗");
return `${answer.status} ${mark}`;
}
// Port 0: the OS picks a free port, so the demo never collides with a server.
const expressServer = createExpressApp().listen(0);
await once(expressServer, "listening");
// address() is a string only for pipes and null before listening.
const address = expressServer.address();
if (address === null || typeof address === "string") {
throw new Error("Express is not listening on a TCP port");
}
const expressUrl = `http://localhost:${address.port}`;
const fastify = createFastifyApp();
const fastifyUrl = await fastify.listen({ port: 0 });
// /boom logs its stack through console.error. That log is silenced in the table
// and shown once below, next to the responses. Any other log is a real failure,
// so it stays visible.
const consoleError = console.error.bind(console);
console.log(
styleText("dim", `${"".padEnd(LABEL_WIDTH)} express fastify code`),
);
let failures = 0;
for (const c of CASES) {
if (c === BOOM) {
console.error = () => {};
}
const e = await send(expressUrl, c);
const f = await send(fastifyUrl, c);
console.error = consoleError;
const sameBody = isDeepStrictEqual(
withoutRequestId(e.body),
withoutRequestId(f.body),
);
const expectedCode = codeOf(e.body) === c.code && codeOf(f.body) === c.code;
const passed =
e.status === c.status && f.status === c.status && expectedCode && sameBody;
if (!passed) {
failures++;
}
const code = codeOf(e.body) ?? "—";
console.log(
`${c.label.padEnd(LABEL_WIDTH)} ` +
`${statusCell(e, c.status)} ${statusCell(f, c.status)} ` +
(expectedCode
? code
: styleText("red", `${code} (expected ${c.code ?? "none"})`)) +
(sameBody ? "" : styleText("red", " DIFFERENT BODY")),
);
}
console.log(
failures === 0
? styleText(
"green",
`\nAll ${CASES.length} cases match: same status, code and body on both frameworks.`,
)
: styleText("red", `\n${failures} of ${CASES.length} cases failed.`),
);
console.log(
styleText("bold", `\n--- What the handler keeps for ${BOOM.label} ---`),
);
for (const [name, url] of [
["express", expressUrl],
["fastify", fastifyUrl],
] as const) {
console.log(styleText("dim", `\n${name} logged:`));
const { body } = await send(url, BOOM);
console.log(styleText("dim", `${name} answered:`), JSON.stringify(body));
}
expressServer.close();
await fastify.close();
process.exitCode = failures === 0 ? 0 : 1;