Skip to content

Commit 91f4899

Browse files
committed
refactor: improve examples
1 parent 622119f commit 91f4899

File tree

4 files changed

+81
-24
lines changed

4 files changed

+81
-24
lines changed

examples/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"scripts": {
66
"dev:handler": "node src/withHandler.js",
77
"dev:middleware": "node src/withMiddleware.js",
8-
"dev:custom": "node src/withCustomMiddleware.js"
8+
"dev:custom-middlware": "node src/withCustomMiddleware.js"
99
},
1010
"dependencies": {
1111
"express": "^4.18.2",

examples/src/withCustomMiddleware.js

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
UnauthorizedError,
55
ForbiddenError,
66
ValidationError,
7+
NotFoundError,
78
} from "http-error-handler";
89

910
const app = express();
@@ -21,24 +22,36 @@ const requireAuth = (req, _res, next) => {
2122
};
2223

2324
const validateUser = (req, _res, next) => {
24-
const { email, password } = req.body;
25-
if (!email || !password) {
26-
throw new ValidationError("Missing required fields", {
27-
email: !email ? "Email is required" : undefined,
28-
password: !password ? "Password is required" : undefined,
29-
});
25+
const { email, username } = req.body;
26+
const errors = {};
27+
28+
if (!email?.trim()) {
29+
errors.email = "Email is required";
30+
} else if (!email.includes("@")) {
31+
errors.email = "Invalid email format";
3032
}
31-
if (!email.includes("@")) {
32-
throw new ValidationError("Invalid email format", {
33-
email: "Must be a valid email address",
34-
});
33+
34+
if (!username?.trim()) {
35+
errors.username = "Username is required";
36+
} else if (username.length < 3) {
37+
errors.username = "Username must be at least 3 characters long";
3538
}
39+
40+
if (Object.keys(errors).length > 0) {
41+
throw new ValidationError("Invalid user data", errors);
42+
}
43+
3644
next();
3745
};
3846

3947
app.get("/users/:id", requireAuth, (req, _res, next) => {
4048
try {
4149
const { id } = req.params;
50+
if (!id.match(/^\d+$/)) {
51+
throw new ValidationError("Invalid user ID", {
52+
id: "User ID must be numeric",
53+
});
54+
}
4255
throw new NotFoundError("User not found", { id });
4356
} catch (error) {
4457
next(error);
@@ -49,9 +62,19 @@ app.post("/users", requireAuth, validateUser, (req, res, next) => {
4962
try {
5063
const { role } = req.query;
5164
if (role === "admin") {
52-
throw new ForbiddenError("Insufficient permissions");
65+
throw new ForbiddenError("Insufficient permissions", {
66+
requiredRole: "superadmin",
67+
providedRole: role,
68+
});
5369
}
54-
res.status(201).json({ message: "User created" });
70+
res.status(201).json({
71+
message: "User created successfully",
72+
user: {
73+
email: req.body.email,
74+
username: req.body.username,
75+
role: role || "user",
76+
},
77+
});
5578
} catch (error) {
5679
next(error);
5780
}
@@ -61,11 +84,15 @@ app.use(
6184
errorMiddleware({
6285
includeStack: process.env.NODE_ENV !== "production",
6386
onError: async (error) => {
64-
console.error(`[${new Date().toISOString()}] Error:`, error);
87+
console.error(`[${new Date().toISOString()}] Error:`, {
88+
type: error.constructor.name,
89+
message: error.message,
90+
details: error.details || {},
91+
});
6592
},
6693
})
6794
);
6895

69-
app.listen(3002, () => {
70-
console.log("Server running on http://localhost:3002");
96+
app.listen(3003, () => {
97+
console.log("Server running on http://localhost:3003");
7198
});

examples/src/withHandler.js

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,11 @@ app.post("/products", async (req, res) => {
3838
const { name, price } = req.body;
3939
const errors = {};
4040

41-
if (!name) errors.name = "Name is required";
42-
if (!price) errors.price = "Price is required";
41+
if (!name?.trim()) errors.name = "Name is required";
42+
if (typeof price !== "number" || price <= 0) {
43+
errors.price = "Price must be a positive number";
44+
}
45+
4346
if (Object.keys(errors).length > 0) {
4447
throw new ValidationError("Invalid product data", errors);
4548
}
@@ -50,6 +53,6 @@ app.post("/products", async (req, res) => {
5053
}
5154
});
5255

53-
app.listen(3000, () => {
54-
console.log("Server running on http://localhost:3000");
56+
app.listen(3001, () => {
57+
console.log("Server running on http://localhost:3001");
5558
});

examples/src/withMiddleware.js

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ import {
88
const app = express();
99
app.use(express.json());
1010

11-
app.get("/with-middleware", (req, res, next) => {
11+
app.get("/with-middleware", (_req, _res, next) => {
1212
try {
1313
throw new NotFoundError("Resource not found");
1414
} catch (error) {
1515
next(error);
1616
}
1717
});
1818

19-
app.get("/users/:id", (req, res, next) => {
19+
app.get("/users/:id", (req, _res, next) => {
2020
try {
2121
const { id } = req.params;
2222
if (!id.match(/^\d+$/)) {
@@ -28,6 +28,33 @@ app.get("/users/:id", (req, res, next) => {
2828
}
2929
});
3030

31+
app.post("/users/register", (req, _res, next) => {
32+
try {
33+
const { email, username } = req.body;
34+
const errors = {};
35+
36+
if (!email?.trim()) {
37+
errors.email = "Email is required";
38+
} else if (!email.includes("@")) {
39+
errors.email = "Invalid email format";
40+
}
41+
42+
if (!username?.trim()) {
43+
errors.username = "Username is required";
44+
} else if (username.length < 3) {
45+
errors.username = "Username must be at least 3 characters long";
46+
}
47+
48+
if (Object.keys(errors).length > 0) {
49+
throw new ValidationError("Invalid registration data", errors);
50+
}
51+
52+
throw new Error("Database connection failed");
53+
} catch (error) {
54+
next(error);
55+
}
56+
});
57+
3158
app.use(
3259
errorMiddleware({
3360
onError: async (error) => {
@@ -36,6 +63,6 @@ app.use(
3663
})
3764
);
3865

39-
app.listen(3001, () => {
40-
console.log("Server running on http://localhost:3001");
66+
app.listen(3002, () => {
67+
console.log("Server running on http://localhost:3002");
4168
});

0 commit comments

Comments
 (0)