Step 9

Let's update the route handlers for "notes" as follows.

First, update the handler for GET /api/notes:

  router.get("/api/notes", checkToken, async (req, res) => {
    const { query } = req.query;
-   const data = await notes.readAll(query);
+   const data = await notes.readAll(req.user.sub, query);
    res.json({ data: data ? data : [] });
  });

Note req.user.sub contains the ID of the user object that decoded out of the authorization (bearer) token.

Next, update the handler for POST /api/notes:

  router.post("/api/notes", checkToken, async (req, res) => {
    try {
      const { title, text } = req.body;
-     const data = await notes.create({ title, text });
+     const data = await notes.create({ title, text, author: req.user.sub });
      res.status(201).json({ data });
    } catch (err) {
      res.status(err.status).json({ message: err.message });
    }
  });

Next, update the handler for DELETE /api/notes/:id:

  router.delete("/api/notes/:id", checkToken, async (req, res) => {
    try {
      const { id } = req.params;
-     const data = await notes.delete(id);
+     const data = await notes.delete(req.user.sub, id);
      res.json({ data });
    } catch (err) {
      res.status(err.status).json({ message: err.message });
    }
  });

Next, update the handler for PUT /api/notes/:id:

  router.put("/api/notes/:id", checkToken, async (req, res) => {
    try {
      const { id } = req.params;
      const { title, text } = req.body;
-     const data = await notes.update(id, { title, text });
+     const data = await notes.update(req.user.sub, id, { title, text });
      res.json({ data });
    } catch (err) {
      res.status(err.status).json({ message: err.message });
    }
  });

Finally, rewrite the handler for GET /api/notes/:id:

router.get("/api/notes/:id", checkToken, async (req, res) => {
  try {
    const { id } = req.params;
    const data = await notes.read(req.user.sub, id);
    res.json({ data });
  } catch (err) {
    res.status(err.status).json({ message: err.message });
  }
});

Save all the changes and reset the server. Then, try the API in Postman. In particular, try to perform CRUD operations on notes. Ensure, e.g., a user can update their note but not a note of another user.