- You will realize that, in our previous exercise, we had to post the whole resource just to change a part of it. A better way of doing this is using PATCH, so that the payload only contains what is required. Let's now create a PATCH route:
{
method: 'PATCH',
handler: (request, reply) =>
{
…
Object.keys(request.payload).forEach(key =>
{
if (key in todo)
{
todo[key] = request.payload[key];
…
return reply({ message: 'patched' });
},
}
Use the todo.js file for your reference at Code/Lesson-2/exercise-c1/routes.
- Now, you can provide any of the keys and their values, and they will be updated respectively. For example, make the following request, only changing the title of the first todo:
- You should get the following response:
{
"message": "patched"
}
- And when you do a GET on http://localhost:8000/todo/1, you should get the updated resource: