Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
**/node_modules
.DS_Store
**/.DS_Store
64 changes: 64 additions & 0 deletions custom-written-middleware/express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import express from "express";
const app = express();

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

const parseJSON = (req, res, next) => {
const bodyBytes = [];
req.on("data", (chunk) => bodyBytes.push(...chunk));
req.on("end", () => {
const bodyString = String.fromCharCode(...bodyBytes);
let body;
try {
body = JSON.parse(bodyString);
} catch (error) {
console.error(`Failed to parse body ${bodyString} as JSON: ${error}`);
res.status(400).send("Expected body to be JSON.");
return;
}
if (
typeof body != "object" ||
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 I pass a string like {"blah": 2}, this is a valid json string so it reaches this part of the code, but it crashes here because there's no .some() on an object, only arrays. Could you improve the input validation?

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.

Got it. The middleware now checks if the request body is an array. I missed in the requirements that we should reject requests when the POST body is not a JSON array.
I've also updated the error message accordingly.

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.

Great! This solution looks good now

body.some((element) => typeof element !== "string")
) {
console.error(
`Failed to extract text of the message from post body: ${bodyString}`
);
res
.status(400)
.send("Expected body to be a JSON object containing key message.");
return;
}
req.body = body;

next();
});
};

app.use(assignHeader);
app.use(parseJSON);

app.post("/", (req, res) => {
let message = [];
if (req.username) {
message.push(`You are authenticated as ${req.username}`);
} else {
message.push("You are not authenticated.");
}
if (req.body.length > 0) {
message.push(
`You have requested information about ${
req.body.length
} subjects: ${req.body.join(", ")}\n`
);
} else {
message.push("You have requested information about 0 subjects.\n");
}
res.send(message.join("\n\n"));
});

app.listen(3000, () => {
console.error(`server listening on port 3000`);
});
37 changes: 37 additions & 0 deletions off-the-shelf-middleware/express.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import express from "express";
const app = express();

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

app.use(assignHeader);
app.use(express.json());

// add `-H 'Content-Type: application/json'` to curl request
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.

What does this comment mean? If this is a test case I would suggest moving it to a test file, rather than leaving it as a comment inline

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.

yeah, I agree. Since I don't have any tests in this repo, I decided to move it to the readme file because that comment is more like an instruction.

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.

Yes, that kind of comment is more suited to the readme. Good idea

//curl -X POST --data '["Bees"]' -H 'Content-Type: application/json' -H "X-Username: Ahmed" http://localhost:3000
// this will match Content-Type header with the type option.

app.post("/", (req, res) => {
let message = [];
if (req.username) {
message.push(`You are authenticated as ${req.username}`);
} else {
message.push("You are not authenticated.");
}
if (req.body.length > 0) {
message.push(
`You have requested information about ${
req.body.length
} subjects: ${req.body.join(", ")}\n`
);
} else {
message.push("You have requested information about 0 subjects.\n");
}
res.send(message.join("\n\n"));
});

app.listen(3000, () => {
console.error(`server listening on port 3000`);
});
Loading