Exercise 10: Deleting a Resource with DELETE

  1. When we want to delete a resource, we use the DELETE method. Let's create a DELETE route:
{
method: 'DELETE',
path: '/todo/{id}',
handler: (request, reply) => {
const index = request.params.id - 1;
delete todoList[index]; // replaces with `undefined`
return reply({ message: 'deleted' });
},
},

Use the 
exercise-c1 folder for your reference at Code/Lesson-2.
  1. Now go to Insomnia and test it—you should get this response:
  1. Now try accessing the previously deleted resources—you should get a 404 error. However, in our previous GET route (in Exercise 6: Getting a Specific Resource), we did not cater for this, so let's go and make a modification to our GET: /todo/{id} route:
{
method: 'GET',
path: '/todo/{id}',
handler: (request, reply) =>
{
const id = request.params.id - 1;
// should return 404 error if item is not found
if (todoList[id]) return reply(todoList[id]);
return reply({ message: 'Not found' }).code(404);
}
}
Use the todo.js file for your reference at Code/Lesson-2/exercise-c1/routes.

Don't worry about the status code, 404, if you have never come across it. We are going to go through the major status codes in our last subsection of this section.
  1. Remember, the server will reload this time, therefore, the deleted resource will still be brought back, so go back and repeat step 2.
  2. When you now do a GET request to http://localhost:8000/todo/1, you should see this:
{
"message": "Not found"
}
Short Closing Note on Insomnia
You should be able to access all your previous requests under History. Click on the Time icon in the top-right corner.
..................Content has been hidden....................

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