Performance: PUT and PATCH route handling
This affects server response time and client perceived latency when updating resources via HTTP routes.
app.patch('/user/:id', (req, res) => { // expects partial user data const partialUpdate = req.body; // update only provided fields db.updateUserFields(req.params.id, partialUpdate); res.sendStatus(200); });
app.put('/user/:id', (req, res) => { // expects full user object const updatedUser = req.body; // replace entire user in DB db.updateUser(req.params.id, updatedUser); res.sendStatus(200); });
| Pattern | Payload Size | Server Processing | Network Latency | Verdict |
|---|---|---|---|---|
| PUT full update | Large (full resource) | High (process entire object) | High (larger data sent) | [X] Bad |
| PATCH partial update | Small (only changes) | Low (process few fields) | Low (smaller data sent) | [OK] Good |
PUT and PATCH methods in Express route handling?PUT is designed to replace the entire resource with the new data sent in the request.PATCH behaviorPATCH updates only the fields specified in the request, leaving other fields unchanged.PUT replaces the entire resource, while PATCH updates only specified fields. -> Option BPATCH route in Express to update a user by ID?PATCH is used to update parts of a resource, so the route should use app.patch./:id to specify which user to update, and the handler function is correctly defined.PATCH request to /product/5 with JSON body {"price": 20}?
const products = { 5: { name: "Pen", price: 10, stock: 100 } };
app.patch('/product/:id', (req, res) => {
const id = req.params.id;
Object.assign(products[id], req.body);
res.json(products[id]);
});Object.assign to update the product with fields from req.body. The JSON body contains {"price": 20}, so only the price changes.PUT route handler?
app.put('/item/:id', (req, res) => {
const id = req.params.id;
items[id] = req.body;
res.send('Item updated');
});
Assuming items is an object storing item data.express.json() middleware, req.body will be undefined for JSON requests.items[id] = req.body will set the item to undefined, causing data loss or errors.req.body will be undefined. -> Option DPUT route to replace a user profile but keep the id field unchanged. Which approach correctly handles this in Express?PUT semanticsPUT replaces the entire resource, so the user object will be overwritten by req.body.id fieldid should not change, after overwriting, manually set user.id back to the original value.req.body except manually set id back after assignment. -> Option APass the test and this pattern moves unknown