Repository navigation
Expand file tree
/
Copy pathapp.ts
More file actions
64 lines (49 loc) · 1.65 KB
/
Copy pathapp.ts
File metadata and controls
64 lines (49 loc) · 1.65 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
import { randomUUID } from "node:crypto";
import express, { type Express } from "express";
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";
// Every request carries an id, like Fastify's request.id.
declare global {
namespace Express {
interface Request {
id: string;
}
}
}
// Builds the app without listening, so the server and the demo can each start it.
export function createExpressApp(): Express {
const users = new UserRepository();
const registerUser = new RegisterUser({ users });
const getUser = new GetUser({ users });
const app = express();
// First, so even a request with a malformed body has an id.
app.use((req, _res, next) => {
req.id = randomUUID();
next();
});
app.use(express.json());
app.post("/users", (req, res) => {
const result = registerUser.execute(req.body);
if (!result.ok) {
return sendProblem(req, res, result.error);
}
res.status(201).json(result.value);
});
app.get("/users/:id", (req, res) => {
const result = getUser.execute({ id: req.params.id });
if (!result.ok) {
return sendProblem(req, res, result.error);
}
res.status(200).json(result.value);
});
// In Express 5 a rejected promise reaches the error handler on its own.
// Express 4 needed a wrapper or a try/catch for this.
app.get("/boom", async () => {
throw new Error("database connection refused");
});
app.use(notFoundHandler);
app.use(errorHandler);
return app;
}