Chained Route Handlers Using Express
While Building my own RESTful API, Today I have learned about Route handlers in express which creates standardized and mountable route handlers.
In this, we use a routing class of express and use the get(), post()and delete() methods and inside the parenthesis, I write a function that will do all the other stuff.
app
.route("/articles")
.get(async (req, res) => {
try {
const foundArticles = await Article.find();
// console.log(foundArticles);
res.send(foundArticles);
} catch (err) {
// console.log(err);
res.send(err);
}
})
.post(function (req, res) {
// Creating new article in database
const newArticle = new Article({
title: req.body.title,
content: req.body.content,
});
newArticle
.save()
.then((newArticle) => {
res.send("Successfully added a new article");
})
.catch((err) => {
res.send(err);
});
})
.delete(function (req, res) {
Article.deleteMany()
.then(function () {
res.send("Articles has been deleted");
})
.catch(function (err) {
res.send(err);
});
});