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
1 change: 1 addition & 0 deletions custome-middlewares/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
16 changes: 16 additions & 0 deletions custome-middlewares/dist/custom-middleware/array-validator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const arrayValidator = (req, res, next) => {
const body = req.body;
// 1. Is it a valid array?
if (!Array.isArray(body)) {
return res.status(400).send("Bad Request: Body must be a JSON array.");
}
// 2. Are all items inside the array strings?
const allStrings = body.every((item) => typeof item === "string");
if (!allStrings) {
return res
.status(400)
.send("Bad Request: All array elements must be strings.");
}
next();
};
export default arrayValidator;
13 changes: 13 additions & 0 deletions custome-middlewares/dist/custom-middleware/username-validator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const usernameLoader = (req, res, next) => {
const usernameHeader = req.headers["x-username"];
if (typeof usernameHeader === "string") {
req.username = usernameHeader;
}
if (!req.username) {
return res
.status(401)
.send("Unauthorized: You must provide a valid x-username header.");
}
next();
};
export default usernameLoader;
23 changes: 23 additions & 0 deletions custome-middlewares/dist/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import express from "express";
import arrayValidator from "./custom-middleware/array-validator.js";
import usernameLoader from "./custom-middleware/username-validator.js";
const app = express();
const port = 3000;
app.use(express.json());
app.post("/", usernameLoader, arrayValidator, (req, res) => {
const subjects = req.body;
const count = subjects.length;
const subjectList = subjects.join(", ");
// 1. Format the authentication message using the custom header middleware
let authMessage = req.username
? `You are authenticated as ${req.username}.`
: "You are not authenticated.";
// 2. Format the subject list counts from the array validator middleware
let subjectMessage = count === 1
? `You have requested information about 1 subject: ${subjectList}.`
: `You have requested information about ${count} subjects${count > 0 ? ": " + subjectList : "."}`;
res.send(`${authMessage}\n\n${subjectMessage}`);
});
app.listen(port, () => {
console.log(`Middleware exercises server running on port ${port}`);
});
Loading
Loading