Repository navigation
Expand file tree
/
Copy pathapp.ts
More file actions
50 lines (37 loc) · 1.5 KB
/
Copy pathapp.ts
File metadata and controls
50 lines (37 loc) · 1.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
import { randomUUID } from "node:crypto";
import Fastify, { type FastifyInstance } from "fastify";
import { GetUser } from "../users/get-user.js";
import { RegisterUser } from "../users/register-user.js";
import { UserRepository } from "../users/user.repository.js";
import { errorHandler, notFoundHandler, sendProblem } from "./error-handler.js";
// Builds the app without listening, so the server and the demo can each start it.
export function createFastifyApp(): FastifyInstance {
const users = new UserRepository();
const registerUser = new RegisterUser({ users });
const getUser = new GetUser({ users });
const app = Fastify({
// A UUID like Express's, instead of the default "req-1", "req-2"...
genReqId: () => randomUUID(),
});
app.setErrorHandler(errorHandler);
app.setNotFoundHandler(notFoundHandler);
app.post("/users", (request, reply) => {
const result = registerUser.execute(request.body);
if (!result.ok) {
return sendProblem(request, reply, result.error);
}
return reply.code(201).send(result.value);
});
app.get<{ Params: { id: string } }>("/users/:id", (request, reply) => {
const result = getUser.execute({ id: request.params.id });
if (!result.ok) {
return sendProblem(request, reply, result.error);
}
return reply.code(200).send(result.value);
});
// A rejected promise reaches the error handler, as in Express 5.
app.get("/boom", async () => {
throw new Error("database connection refused");
});
return app;
}