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 .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
\node_modules
59 changes: 59 additions & 0 deletions CustomMiddlewareVersion/customeMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import express from "express";

const app = express();

// Built-in middleware to parse JSON bodies
app.use(express.json());

//extract username from header
const extractUsername = (req, res, next) => {
const usernameHeader = req.headers["x-username"];
req.username = usernameHeader ? usernameHeader : null;
next();
};

// validate JSON array from POST body
const validateJsonArray = (req, res, next) => {
if (!Array.isArray(req.body)) {
return res.status(400).send("Expected a JSON array.");
}

const allStrings = req.body.every((item) => typeof item === "string");
if (!allStrings) {
return res.status(400).send("Array must contain only strings.");
}

next();
};

// Use the middlewares
app.use(extractUsername);
app.use(validateJsonArray);

// Route handler
app.post("/", (req, res) => {
const messages = [];

messages.push(
req.username
? `You are authenticated as ${req.username}.`
: "You are not authenticated."
);

if (req.body.length > 0) {
messages.push(
`You have requested information about ${req.body.length} subject${
req.body.length > 1 ? "s" : ""
}: ${req.body.join(", ")}.`
);
} else {
messages.push("You have requested information about 0 subjects.");
}

res.send(messages.join("\n\n"));
});

// Start server
app.listen(3000, () => {
console.log("Server running on port 3000");
});
38 changes: 38 additions & 0 deletions off-the-shelfMiddleware/builtIn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import express from "express";
const app = express();

const header = (req, res, next) => {
const userNameHeader = req.header["x-username"];
req.username = userNameHeader ? userNameHeader : null;
next();
};
app.use(header);
app.use(express.json()); //built -in json parser

app.post("/", (req, res) => {
const subjects = Array.isArray(req.body) ? req.body : [];

if (!subjects.every((item) => typeof item === "string")) {
return res.status(400).send("Expected an array of strings.");
}

const messages = [];
messages.push(
req.username
? `You are authenticated as ${req.username}`
: "You are not authenticated."
);
messages.push(
subjects.length > 0
? `You have requested information about ${
subjects.length
} subjects: ${subjects.join(", ")}`
: "You have requested information about 0 subjects."
);

res.send(messages.join("\n\n"));
});

app.listen(3001, () => {
console.log("Server running on port 3001 (built-in middleware version)");
});
Loading
Loading