Exercise 15: Reading from the Database

In this exercise, we're going to write the routes for:

  • Listing all todo for a particular user
  • Getting details for a single todo item
  • Listing items for a particular todo

We will use a number Knex methods:

  • Knex('<table_name>'), this is equivalent to 'SELECT * FROM <table_name>'
  • .where(), used for adding the where clause to the query
  1. To get a list of all todo, we will modify our previous GET: /todo route. Here, you only want to list todo items for a particular authenticated user. For now, we will be using our hardcoded test user:
{
method: 'GET',
path: '/todo',
handler: async (request, reply) =>
{
const userId = 1; // hard-coded
const todos = await Knex('todo')
.where('user_id', userId);
return reply(todos);
},
},
  1. Let's modify the route for getting a single todo item, GET: /todo/<id>:
{
method: 'GET',
path: '/todo/{id}',
...
.where({
id: id,
user_id: userId
});
if (todo) return reply(todo);
return reply({ message: 'Not found' }).code(404);
},
},

You can find the complete code from the todo.js file at Code/Lesson-3/exercise-a/routes.
We are using array destructuring here too, since the result, if any, will be an array of length 1, so we're getting the first and only element from the array with: const [ todo ] = ...
  1. Now, let's add the route object for getting a list of items for a particular todo, preferably just after the route for adding a todo item that we did in Exercise 14: Creating a Record:
{
method: 'GET',
path: '/todo/{id}/item',
handler: async (request, reply) =>
{
const todoId = request.params.id;
const items = await Knex('todo_item')
.where('todo_id', todoId);
return reply(items);
},
},
  1. Now, let's test the route:
..................Content has been hidden....................

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