Skip to content

Commit e3efea2

Browse files
committed
refactor: Improve POST /messages validation with type checking
- Add check for req.body existence before destructuring - Add type validation to ensure text and sender are strings - Replace simple falsy check with .trim() for whitespace validation - Return specific error messages for each validation failure - Improve error handling clarity with separate validation steps - Prevent type coercion errors and invalid data submission
1 parent 8972d95 commit e3efea2

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

chat-app/backend/server.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,20 @@ app.use(cors());
1414
app.use(express.json());
1515

1616
app.post("/messages", (req, res) => {
17+
// Check if re.body exists at all
18+
if (!req.body) {
19+
return res.status(400).send("No body provided");
20+
}
21+
1722
const { text, sender } = req.body;
1823

19-
// The validation
20-
if (!text || text.length === 0 || !sender || sender.length === 0) {
24+
// Check if the inputs are strings
25+
if (typeof text !== "string" || typeof sender !== "string") {
26+
return res.status(400).send("Inputs must be strings");
27+
}
28+
29+
// Check if the inputs are not a falsy value
30+
if (!text.trim() || !sender.trim()) {
2131
return res.status(400).send("Please provide both text and a sender name.");
2232
}
2333

0 commit comments

Comments
 (0)