Habit tracker API: Get & Post

mtee

Margaret W.N

Posted on July 27, 2020

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

💖 💪 🙅 🚩
mtee
Margaret W.N

Posted on July 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Generating a Json Web Token
100daysofcode Generating a Json Web Token

August 15, 2020

The C in MVC: Controllers
100daysofcode The C in MVC: Controllers

August 12, 2020

User signup & Password Hashing
100daysofcode User signup & Password Hashing

August 8, 2020

User Login: Trial and Error
100daysofcode User Login: Trial and Error

August 10, 2020

Habit tracker API: Updating data
100daysofcode Habit tracker API: Updating data

July 28, 2020