There's more...

There is one more HTTP method supported by resource-router-middleware, that is, the PATCH method. There is quite a lot of confusion about when to use PATCH versus when to use PUT in your REST API. Let's review the official RFC 5789 specification for PATCH and PUT to better understand the difference:

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. For more information, you can visit the following link:
https://tools.ietf.org/html/rfc5789

In short, PUT is considered a replacement for a resource, whereas PATCH is considered a modification to an existing resource. Technically speaking, our REST API is not in compliance with this definition. This is a surprisingly common situation for web application APIs; PUT as an update operation is often treated as PATCH, although they are technically very different ways to change the state of a resource. To correct this, we will need to introduce a new modify method to our middleware and change our update method:

...
update
: function(req, res) {
var id = req.params[resourceId];
find(id, function(item, i) {
if (item) {
store.splice(i, 1);
item.id = id;
store.push(item)
;
return res.status(204).send('Replaced');
} else {
res.status(404).send('Not found');
}
});
},

modify : function(req, res) {
var id = req.params[resourceId];
find(id, function(item, i) {

if (item) {
Object.assign(store[i], req.body);
return res.status(204).send('Accepted');
} else {

res.status(404).send('Not found');
}

});
},
...

This change allows our PUT update calls to completely rewrite an object, except for its ID, whereas PATCH will only modify an existing resource, including being able to update the ID. Ultimately, we end up with a slightly more flexible REST API, but the choice of how you implement your API's logic is up to you.

You can learn more about resource-router-middleware, including some nice ES6 friendly options, from the official GitHub repository:
https://github.com/developit/resource-router-middleware
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.204.201