Skip to content

Commit 91d64b3

Browse files
⬆️ Update dependency express to v5 (#391)
* ⬆️ Update dependency express to v5 * refactor: Simplify response handling in API controllers and middleware --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Edwin Hernandez <edwinhern.16@gmail.com>
1 parent 8ae6a17 commit 91d64b3

File tree

9 files changed

+148
-187
lines changed

9 files changed

+148
-187
lines changed

.env.template

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,5 @@ HOST="localhost" # Hostname for the server
77
CORS_ORIGIN="http://localhost:*" # Allowed CORS origin, adjust as necessary
88

99
# Rate Limiting
10-
COMMON_RATE_LIMIT_WINDOW_MS="1000" # Window size for rate limiting (ms)
10+
COMMON_RATE_LIMIT_WINDOW_MS="1000" # Window size for rate limiting (ms)
1111
COMMON_RATE_LIMIT_MAX_REQUESTS="20" # Max number of requests per window per IP

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"main": "index.ts",
99
"private": true,
1010
"scripts": {
11-
"build": "tsup",
11+
"build": "tsc && tsup",
1212
"start:dev": "tsx watch --clear-screen=false src/index.ts | pino-pretty",
1313
"start:prod": "node dist/index.js",
1414
"lint": "biome lint",
@@ -23,7 +23,7 @@
2323
"cors": "2.8.5",
2424
"dotenv": "16.5.0",
2525
"envalid": "8.0.0",
26-
"express": "4.21.2",
26+
"express": "5.1.0",
2727
"express-rate-limit": "7.5.0",
2828
"helmet": "8.1.0",
2929
"http-status-codes": "2.3.0",

pnpm-lock.yaml

Lines changed: 128 additions & 156 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/api/healthCheck/healthCheckRouter.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { z } from "zod";
44

55
import { createApiResponse } from "@/api-docs/openAPIResponseBuilders";
66
import { ServiceResponse } from "@/common/models/serviceResponse";
7-
import { handleServiceResponse } from "@/common/utils/httpHandlers";
87

98
export const healthCheckRegistry = new OpenAPIRegistry();
109
export const healthCheckRouter: Router = express.Router();
@@ -18,5 +17,5 @@ healthCheckRegistry.registerPath({
1817

1918
healthCheckRouter.get("/", (_req: Request, res: Response) => {
2019
const serviceResponse = ServiceResponse.success("Service is healthy", null);
21-
return handleServiceResponse(serviceResponse, res);
20+
res.status(serviceResponse.statusCode).send(serviceResponse);
2221
});

src/api/user/userController.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
11
import type { Request, RequestHandler, Response } from "express";
22

33
import { userService } from "@/api/user/userService";
4-
import { handleServiceResponse } from "@/common/utils/httpHandlers";
54

65
class UserController {
76
public getUsers: RequestHandler = async (_req: Request, res: Response) => {
87
const serviceResponse = await userService.findAll();
9-
return handleServiceResponse(serviceResponse, res);
8+
res.status(serviceResponse.statusCode).send(serviceResponse);
109
};
1110

1211
public getUser: RequestHandler = async (req: Request, res: Response) => {
1312
const id = Number.parseInt(req.params.id as string, 10);
1413
const serviceResponse = await userService.findById(id);
15-
return handleServiceResponse(serviceResponse, res);
14+
res.status(serviceResponse.statusCode).send(serviceResponse);
1615
};
1716
}
1817

src/common/__tests__/errorHandler.test.ts

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,27 +19,20 @@ describe("Error Handler Middleware", () => {
1919
});
2020

2121
app.use(errorHandler());
22-
app.use("*", (req, res) => res.status(StatusCodes.NOT_FOUND).send("Not Found"));
2322
});
2423

25-
describe("Handling unknown routes", () => {
26-
it("returns 404 for unknown routes", async () => {
27-
const response = await request(app).get("/this-route-does-not-exist");
28-
expect(response.status).toBe(StatusCodes.NOT_FOUND);
29-
});
24+
it("returns 404 for unknown routes", async () => {
25+
const response = await request(app).get("/this-route-does-not-exist");
26+
expect(response.status).toBe(StatusCodes.NOT_FOUND);
3027
});
3128

32-
describe("Handling thrown errors", () => {
33-
it("handles thrown errors with a 500 status code", async () => {
34-
const response = await request(app).get("/error");
35-
expect(response.status).toBe(StatusCodes.INTERNAL_SERVER_ERROR);
36-
});
29+
it("handles thrown errors with a 500 status code", async () => {
30+
const response = await request(app).get("/error");
31+
expect(response.status).toBe(StatusCodes.INTERNAL_SERVER_ERROR);
3732
});
3833

39-
describe("Handling errors passed to next()", () => {
40-
it("handles errors passed to next() with a 500 status code", async () => {
41-
const response = await request(app).get("/next-error");
42-
expect(response.status).toBe(StatusCodes.INTERNAL_SERVER_ERROR);
43-
});
34+
it("handles errors passed to next() with a 500 status code", async () => {
35+
const response = await request(app).get("/next-error");
36+
expect(response.status).toBe(StatusCodes.INTERNAL_SERVER_ERROR);
4437
});
4538
});

src/common/__tests__/requestLogger.test.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ describe("Request Logger Middleware", () => {
1010

1111
beforeAll(() => {
1212
app.use(requestLogger);
13-
app.get("/success", (req, res) => res.status(StatusCodes.OK).send("Success"));
13+
app.get("/success", (_req, res) => {
14+
res.status(StatusCodes.OK).send("Success");
15+
});
1416
app.get("/redirect", (req, res) => res.redirect("/success"));
1517
app.get("/error", () => {
1618
throw new Error("Test error");

src/common/middleware/errorHandler.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { ErrorRequestHandler, RequestHandler } from "express";
22
import { StatusCodes } from "http-status-codes";
33

44
const unexpectedRequest: RequestHandler = (_req, res) => {
5-
res.sendStatus(StatusCodes.NOT_FOUND);
5+
res.status(StatusCodes.NOT_FOUND).send("Not Found");
66
};
77

88
const addErrorToRequestLog: ErrorRequestHandler = (err, _req, res, next) => {

src/common/utils/httpHandlers.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,6 @@ import type { ZodError, ZodSchema } from "zod";
44

55
import { ServiceResponse } from "@/common/models/serviceResponse";
66

7-
export const handleServiceResponse = (serviceResponse: ServiceResponse<unknown>, response: Response) => {
8-
return response.status(serviceResponse.statusCode).send(serviceResponse);
9-
};
10-
117
export const validateRequest = (schema: ZodSchema) => (req: Request, res: Response, next: NextFunction) => {
128
try {
139
schema.parse({ body: req.body, query: req.query, params: req.params });
@@ -16,6 +12,6 @@ export const validateRequest = (schema: ZodSchema) => (req: Request, res: Respon
1612
const errorMessage = `Invalid input: ${(err as ZodError).errors.map((e) => e.message).join(", ")}`;
1713
const statusCode = StatusCodes.BAD_REQUEST;
1814
const serviceResponse = ServiceResponse.failure(errorMessage, null, statusCode);
19-
return handleServiceResponse(serviceResponse, res);
15+
res.status(serviceResponse.statusCode).send(serviceResponse);
2016
}
2117
};

0 commit comments

Comments
 (0)