Skip to content

refactor: improve examples #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"scripts": {
"dev:handler": "node src/withHandler.js",
"dev:middleware": "node src/withMiddleware.js",
"dev:custom": "node src/withCustomMiddleware.js"
"dev:custom-middlware": "node src/withCustomMiddleware.js"
},
"dependencies": {
"express": "^4.18.2",
Expand Down
55 changes: 39 additions & 16 deletions examples/src/withCustomMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
UnauthorizedError,
ForbiddenError,
ValidationError,
NotFoundError,
} from "http-error-handler";

const app = express();
Expand All @@ -21,37 +22,59 @@ const requireAuth = (req, _res, next) => {
};

const validateUser = (req, _res, next) => {
const { email, password } = req.body;
if (!email || !password) {
throw new ValidationError("Missing required fields", {
email: !email ? "Email is required" : undefined,
password: !password ? "Password is required" : undefined,
});
const { email, username } = req.body;
const errors = {};

if (!email?.trim()) {
errors.email = "Email is required";
} else if (!email.includes("@")) {
errors.email = "Invalid email format";
}
if (!email.includes("@")) {
throw new ValidationError("Invalid email format", {
email: "Must be a valid email address",
});

if (!username?.trim()) {
errors.username = "Username is required";
} else if (username.length < 3) {
errors.username = "Username must be at least 3 characters long";
}

if (Object.keys(errors).length > 0) {
throw new ValidationError("Invalid user data", errors);
}

next();
};

app.get("/users/:id", requireAuth, (req, _res, next) => {
try {
const { id } = req.params;
if (!id.match(/^\d+$/)) {
throw new ValidationError("Invalid user ID", {
id: "User ID must be numeric",
});
}
throw new NotFoundError("User not found", { id });
} catch (error) {
next(error);
}
});

app.post("/users", requireAuth, validateUser, (req, res, next) => {
app.post("/users/register", requireAuth, validateUser, (req, res, next) => {
try {
const { role } = req.query;
if (role === "admin") {
throw new ForbiddenError("Insufficient permissions");
throw new ForbiddenError("Insufficient permissions", {
message: "Only administrators can create admin users",
currentUserRole: "user",
});
}
res.status(201).json({ message: "User created" });
res.status(201).json({
message: "User registered successfully",
user: {
email: req.body.email,
username: req.body.username,
role: role || "user",
},
});
} catch (error) {
next(error);
}
Expand All @@ -61,11 +84,11 @@ app.use(
errorMiddleware({
includeStack: process.env.NODE_ENV !== "production",
onError: async (error) => {
console.error(`[${new Date().toISOString()}] Error:`, error);
console.error(`[${new Date().toISOString()}] Error: ${error.message}`);
},
})
);

app.listen(3002, () => {
console.log("Server running on http://localhost:3002");
app.listen(3003, () => {
console.log("Server running on http://localhost:3003");
});
11 changes: 7 additions & 4 deletions examples/src/withHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ app.post("/products", async (req, res) => {
const { name, price } = req.body;
const errors = {};

if (!name) errors.name = "Name is required";
if (!price) errors.price = "Price is required";
if (!name?.trim()) errors.name = "Name is required";
if (typeof price !== "number" || price <= 0) {
errors.price = "Price must be a positive number";
}

if (Object.keys(errors).length > 0) {
throw new ValidationError("Invalid product data", errors);
}
Expand All @@ -50,6 +53,6 @@ app.post("/products", async (req, res) => {
}
});

app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
app.listen(3001, () => {
console.log("Server running on http://localhost:3001");
});
37 changes: 32 additions & 5 deletions examples/src/withMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ import {
const app = express();
app.use(express.json());

app.get("/with-middleware", (req, res, next) => {
app.get("/with-middleware", (_req, _res, next) => {
try {
throw new NotFoundError("Resource not found");
} catch (error) {
next(error);
}
});

app.get("/users/:id", (req, res, next) => {
app.get("/users/:id", (req, _res, next) => {
try {
const { id } = req.params;
if (!id.match(/^\d+$/)) {
Expand All @@ -28,14 +28,41 @@ app.get("/users/:id", (req, res, next) => {
}
});

app.post("/users/register", (req, _res, next) => {
try {
const { email, username } = req.body;
const errors = {};

if (!email?.trim()) {
errors.email = "Email is required";
} else if (!email.includes("@")) {
errors.email = "Invalid email format";
}

if (!username?.trim()) {
errors.username = "Username is required";
} else if (username.length < 3) {
errors.username = "Username must be at least 3 characters long";
}

if (Object.keys(errors).length > 0) {
throw new ValidationError("Invalid registration data", errors);
}

throw new Error("Database connection failed");
} catch (error) {
next(error);
}
});

app.use(
errorMiddleware({
onError: async (error) => {
console.error(`Error: ${error}`);
console.error(`Error: ${error.message}`);
},
})
);

app.listen(3001, () => {
console.log("Server running on http://localhost:3001");
app.listen(3002, () => {
console.log("Server running on http://localhost:3002");
});
Loading