Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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 custom-middlewares/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules
75 changes: 75 additions & 0 deletions custom-middlewares/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const express = require('express');
const app = express();

const port = process.env.PORT || 3000;


const usernameCustomMiddleware = (req, res, next) => {
const username = req.headers["username"];
req.name = username ? username : null;
next();
}

const jsonBodyMustBeAnArrayMiddleware = (req, res, next) => {
let raw = "";
let chunks = [];

req.on("data", (chunk) => {
chunks.push(chunk);
});

req.on("end", () => {
try {
raw = Buffer.concat(chunks).toString("utf8");
const parsed = JSON.parse(raw);

if (!Array.isArray(parsed)) {
return res.status(400).type("text").send("Bad Request: Expected a JSON array in the request body.");
}

const confirmString = parsed.every(item => typeof item === "string");

if (!confirmString) {
return res.status(400).type("text").send("Bad Request: Expected a JSON array of strings in the request body.");
}

req.body = parsed;
next();

} catch (error) {
return res.status(400).type("text").send("Bad Request: Invalid JSON in the request body.");
}

})

req.on("error", () => {
return res.status(400).type("text").send("Bad Request: Error reading the request body.");
})

}


app.post("/custom-middleware", usernameCustomMiddleware, jsonBodyMustBeAnArrayMiddleware, (req, res) => {
try {

const username = req.name;
const subject = req.body;
const count = subject.length;

const authentication = username
? `You are authenticated as ${username}`
: "You are not authenticated";

let subjectResponse = `You have requested info about ${count} subject${count === 1 ? "" : "s"}`;
subjectResponse += count > 0 ? `: ${subject.join(", ")}.` : `.`;

res.status(200).type("text").send(`\n${authentication}\n${subjectResponse}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you are not authenticated, should the app return a subject list?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okay, good catch! I added an authentication check before building the response. if no username header is provided, the app now returns a 401 unauthorized error immediately, rather than returning the subject list to unauthenticated users. for both case

if (!username) { return res.status(401).type("text").send("Unauthorized: Missing or invalid username in the request headers."); }


} catch (error) {
return res.status(500).type("text").send("Internal Server Error.");
}
})

app.listen(port, () => {
console.log(`Server is running on Port: ${port}`);
})
Loading
Loading