Skip to content
Open
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
627 changes: 627 additions & 0 deletions assignments/03-express-middleware.md

Large diffs are not rendered by default.

764 changes: 764 additions & 0 deletions lessons/03-express-middleware.md

Large diffs are not rendered by default.

75 changes: 75 additions & 0 deletions mentor-guidebook/sample-answers/assignment3/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import express from "express";
import userRoutes from "./routes/userRoutes.js";
import errorHandler from "./middleware/error-handler.js";
import notFound from "./middleware/not-found.js";

global.user_id = null;
global.users = [];
global.tasks = [];

const app = express();

app.use((req, res, next) => {
console.log("Method:", req.method);
console.log("Path:", req.path);
console.log("Query:", req.query);
next();
});
const port = process.env.PORT || 3000;

app.use(express.json());

app.use("/api/users", userRoutes);

app.get("/health", (req, res) => {
res.json({ status: "ok" });
});

app.use(notFound);
app.use(errorHandler);

let server;
if (!process.env.VITEST) {
server = app.listen(port, () =>
console.log(`Server is listening on port ${port}...`),
);

server.on("error", (err) => {
if (err.code === "EADDRINUSE") {
console.error(`Port ${port} is already in use.`);
} else {
console.error("Server error:", err);
}
process.exit(1);
});

let isShuttingDown = false;
async function shutdown(code = 0) {
if (isShuttingDown) return;
isShuttingDown = true;
console.log("Shutting down gracefully...");
try {
await new Promise((resolve) => server.close(resolve));
console.log("HTTP server closed.");
} catch (err) {
console.error("Error during shutdown:", err);
code = 1;
} finally {
console.log("Exiting process...");
process.exit(code);
}
}

process.on("SIGINT", () => shutdown(0));
process.on("SIGTERM", () => shutdown(0));
process.on("uncaughtException", (err) => {
console.error("Uncaught exception:", err);
shutdown(1);
});
process.on("unhandledRejection", (reason) => {
console.error("Unhandled rejection:", reason);
shutdown(1);
});
}

export default app;
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { StatusCodes } from "http-status-codes";

export const register = async (req, res) => {
const existingUser = global.users.find(
(user) => user.email === req.body?.email,
);
if (existingUser) {
return res.status(StatusCodes.BAD_REQUEST).json({ message: "User already exists" });
}

const newUser = { ...req.body };
global.users.push(newUser);

res.status(StatusCodes.CREATED).json({
name: newUser.name,
email: newUser.email,
});
};

export const logon = async (req, res) => {
const { email, password } = req.body;

if (!email || !password) {
return res
.status(StatusCodes.BAD_REQUEST)
.json({ message: "Email and password are required" });
}

const user = global.users.find(
(u) => u.email === email && u.password === password,
);

if (!user) {
return res
.status(StatusCodes.UNAUTHORIZED)
.json({ message: "Invalid credentials" });
}

global.user_id = user;

res.status(StatusCodes.OK).json({
name: user.name,
email: user.email,
});
};

export const logoff = async (req, res) => {
global.user_id = null;
res.sendStatus(StatusCodes.OK);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { StatusCodes } from "http-status-codes";

const errorHandlerMiddleware = (err, req, res, next) => {
console.error(
"Internal server error: ",
err.constructor.name,
JSON.stringify(err, ["name", "message", "stack"]),
);

if (!res.headersSent) {
return res
.status(StatusCodes.INTERNAL_SERVER_ERROR)
.json({ message: "An internal server error occurred." });
}
};

export default errorHandlerMiddleware;
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { StatusCodes } from "http-status-codes";

const notFoundMiddleware = (req, res) => {
return res
.status(StatusCodes.NOT_FOUND)
.json({ message: `You can't do a ${req.method} for ${req.url}.` });
};

export default notFoundMiddleware;
10 changes: 10 additions & 0 deletions mentor-guidebook/sample-answers/assignment3/routes/userRoutes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import express from "express";
import { logon, register, logoff } from "../controllers/userController.js";

const router = express.Router();

router.post("/register", register);
router.post("/logon", logon);
router.post("/logoff", logoff);

export default router;
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import { v4 as uuidv4 } from "uuid";
import dogsRouter from "./routes/dogs.js";
import {
ValidationError,
NotFoundError,
UnauthorizedError,
} from "./errors.js";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const app = express();

app.use((req, res, next) => {
req.requestId = uuidv4();
res.setHeader("X-Request-Id", req.requestId);
next();
});

app.use((req, res, next) => {
const timestamp = new Date().toISOString();
console.log(
`[${timestamp}]: ${req.method} ${req.path} (${req.requestId})`,
);
next();
});

app.use((req, res, next) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("X-Frame-Options", "DENY");
res.setHeader("X-XSS-Protection", "1; mode=block");
next();
});

app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ limit: "1mb", extended: true }));

app.use(
"/images",
express.static(path.join(__dirname, "public/images")),
);

app.use((req, res, next) => {
if (req.method !== "POST") {
return next();
}
const contentType = req.get("Content-Type") || "";
const isJson = contentType.toLowerCase().includes("application/json");
if (!isJson) {
return res.status(400).json({
error: "Content-Type must be application/json",
requestId: req.requestId,
});
}
next();
});

app.use("/", dogsRouter);

app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;

if (statusCode >= 400 && statusCode < 500) {
if (err instanceof ValidationError) {
console.warn("WARN: ValidationError", err.message);
} else if (err instanceof UnauthorizedError) {
console.warn("WARN: UnauthorizedError", err.message);
} else if (err instanceof NotFoundError) {
console.warn("WARN: NotFoundError", err.message);
} else {
console.warn(`WARN: ${err.name}`, err.message);
}
} else {
console.error("ERROR: Error", err.message);
}

const bodyError =
statusCode === 500 ? "Internal Server Error" : err.message;

res.status(statusCode).json({
error: bodyError,
requestId: req.requestId,
});
});

app.use((req, res) => {
res.status(404).json({
error: "Route not found",
requestId: req.requestId,
});
});

if (!process.env.VITEST) {
app.listen(3000, () => console.log("Server listening on port 3000"));
}

export default app;
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
export default [
{
name: "Sweet Pea",
sex: "Female",
color: "Brown",
weight: "55 lbs",
breed: "Labrador Retriever",
age: 3,
story: "Rescued from a local shelter",
goodWithKids: true,
goodWithDogs: true,
goodWithCats: false,
status: "available",
},
{
name: "Luna",
sex: "Female",
weight: "65 lbs",
color: "Black",
breed: "German Shepherd",
age: 5,
story: "Owner could no longer care for her",
goodWithKids: true,
goodWithDogs: false,
goodWithCats: false,
status: "available",
},
{
name: "Max",
weight: "60 lbs",
sex: "Male",
color: "Golden",
breed: "Golden Retriever",
age: 2,
story: "Found as a stray",
goodWithKids: true,
goodWithDogs: true,
goodWithCats: true,
status: "pending",
},
{
name: "Poppy",
weight: "9 lbs",
sex: "Female",
color: "Tricolor",
breed: "Dachshund",
age: 1,
story: "Rescued from a puppy mill",
goodWithKids: false,
goodWithDogs: true,
goodWithCats: false,
status: "available",
},
];
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
this.statusCode = 400;
}
}

export class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = "NotFoundError";
this.statusCode = 404;
}
}

export class UnauthorizedError extends Error {
constructor(message) {
super(message);
this.name = "UnauthorizedError";
this.statusCode = 401;
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import express from "express";
import dogData from "../dogData.js";
import { ValidationError, NotFoundError } from "../errors.js";

const router = express.Router();

router.get("/dogs", (req, res) => {
res.json(dogData);
});

router.post("/adopt", (req, res, next) => {
const { name, address, email, dogName } = req.body;

if (!name || !email || !dogName) {
return next(new ValidationError("Missing required fields"));
}

const dog = dogData.find((d) => d.name === dogName && d.status === "available");
if (!dog) {
return next(
new NotFoundError("Dog not found or not available for adoption"),
);
}

return res.status(201).json({
message: `Adoption request received. We will contact you at ${email} for further details.`,
application: {
name,
address,
email,
dogName,
applicationId: Date.now(),
},
});
});

router.get("/error", (req, res, next) => {
next(new Error("Test error"));
});

export default router;