loading...

Habit tracker API: Get & Post

mtee profile image Margaret W.N ・2 min read

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);
      }
    });  
  });

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);
    })
  })

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);
  });

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

Posted on by:

mtee profile

Margaret W.N

@mtee

Developer | GADs 20 scholar | Diving into backend

Discussion

markdown guide