Habit tracker API: Get & Post
Margaret W.N
Posted on July 27, 2020
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.
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.
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.
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 July 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.