Skip to content

Commit bcc3871

Browse files
feat(users): add PUT /users/:id with validation and 404 handling
Full-replace semantics: name and email are both required as non-empty strings and the email is shape-checked, so a partial body is a 400 rather than a silent half-update. The body is validated before the store lookup because a malformed request is a client error either way. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent efd9c37 commit bcc3871

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

routes/users.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@ const store = require("../db/store");
33

44
const router = express.Router();
55

6+
// Deliberately loose: enough to catch obvious typos without pretending to
7+
// implement full RFC 5322 validation.
8+
const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
9+
10+
function isNonEmptyString(value) {
11+
return typeof value === "string" && value.trim() !== "";
12+
}
13+
614
// GET /users — list every user
715
router.get("/", (req, res) => {
816
res.json(store.getAllUsers());
@@ -32,4 +40,31 @@ router.post("/", (req, res) => {
3240
res.status(201).json(user);
3341
});
3442

43+
// PUT /users/:id — replace a user's details; name and email are both required
44+
router.put("/:id", (req, res) => {
45+
const id = Number(req.params.id);
46+
47+
if (!Number.isInteger(id)) {
48+
return res.status(400).json({ error: "id must be an integer" });
49+
}
50+
51+
const { name, email } = req.body;
52+
53+
if (!isNonEmptyString(name) || !isNonEmptyString(email)) {
54+
return res.status(400).json({ error: "name and email are required" });
55+
}
56+
57+
if (!EMAIL_PATTERN.test(email.trim())) {
58+
return res.status(400).json({ error: "email must be a valid email address" });
59+
}
60+
61+
const user = store.updateUser(id, { name: name.trim(), email: email.trim() });
62+
63+
if (!user) {
64+
return res.status(404).json({ error: "User not found" });
65+
}
66+
67+
res.json(user);
68+
});
69+
3570
module.exports = router;

0 commit comments

Comments
 (0)