DEV Community

Margaret W.N
Margaret W.N

Posted on

Habit tracker API: Get & Post

The journey continues

Moving on with the habit tracker API, I modified the Get function to find and retrieve all habits else return an error.

router.route('/habits')
  .get((req, res) => {
    Habit.find((err, habits) => {
      if (err) {
        return res.send(err);
      } else {
        return res.json(habits);
      }
    });  
  });
Enter fullscreen mode Exit fullscreen mode

Since the database has no data sending a get request to postman returns an empty object.
Alt Text

I'll set up a post function to add and save data to my database.

 .post((req, res) => {
    const habit = new Habit(req.body);

    habit.save((err) => {
      if (err) {
        return res.sendStatus(404);
      }
      return res.json(habit);
    })
  })
Enter fullscreen mode Exit fullscreen mode

Adding data from postman sends back the data with an with an Id.
Alt Text

I'll eventually need to update the habits which creates the need for put, patch and delete function. I'd have to first retrieve data by Id in each of the functions, which would result in duplicate code. To avoid this i'll create middleware to find data by id and pass that data to my route handler.

router.use('/habits/:habitId', (req, res, next) =>  {
  Habit.findById(req.params.habitId, (err, habit) => {
    if (err) {
      return res.send(err);
    }
    if(habit) {
      req.habit = habit;
      return next();
    }
    return res.sendStatus(404);
  })
});

router.route('/habits/:habitId')
  .get((res, req) => { 
    res.json(req.habit);
  });
Enter fullscreen mode Exit fullscreen mode

I'll test this in postman.
Alt Text
And Boom, an error!

After hours of googling i still couldn't fix it so i'll call it a day and try again tomorrow.

Day 11

Top comments (0)