Exercise 18: Cleaning up the Code

Now that we have almost updated all our routes that we had from Chapter 2, Building the API – Part 1, let's now remove all the code that is no longer needed:

  1. Remove the previously hardcoded list of todos:
const todoList = [
...
];
  1. Remove the PUT: /todo/<id> route object:
{
method: 'PUT',
path: '/todo/{id}',
handler: (request, reply) =>
{
const index = request.params.id - 1;
// replace the whole resource with the new one
todoList[index] = request.payload;
return reply({ message: 'updated' });
},
},
  1. Reimplement the DELETE: /todo/<id> route object, very similar to Exercise 17: Deleting a Record; the difference is just the route:
{
method: 'DELETE',
path: '/todo/{id}',
handler: async (request, reply) =>
{
const id = request.params.id;
const deleted = await Knex('todo')
.where('id', id)
.delete();
return reply({ message: 'deleted' });
},
},
Since our SQL query had this line that adds a constraint which is possible when a todo is deleted, all the items for that todo are also deleted:
CREATE TABLE todo_item(
  'id' INT PRIMARY KEY AUTO_INCREMENT,
  'text' VARCHAR(50),
  'done' BOOLEAN,
  'date_created' TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  'todo_id' INT,
  FOREIGN KEY (`todo_id`) REFERENCES `todo` (`id`) ON DELETE CASCADE
);
..................Content has been hidden....................

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