Photo by Markus Winkler on Unsplash
Implementing Unauthenticated Article Routes
#5 Article on the series.
Table of contents
Introduction.
Hello and welcome back. I hope you are well. Still on the project walkthrough, if you missed the first article on this series, you can find it here.
In this article, I will be discussing how unauthenticated users can access articles. I will implement the routes which I like to call "public routes". Let's get started.
Get published article.
/controllers/publicController.js
const articleModel = require("../models/articleModel");
const userModel = require("../models/userModel");
const getPublishedArticle = async (req, res, next) => {
try {
const id = req.params.id;
const article = await articleModel
.findById(id)
.populate("author", "first_name last_name");
if (article.state === "published") {
article.read_count++;
await article.save();
res.status(200).send(article);
} else {
res.send("You can only view published article");
}
} catch (err) {
next(err);
}
};
module.exports = { getPublishedArticle };
The code above starts by importing the article and user models. The getPublishedArticle() function finds an article with a particular id. If the article exists, it is returned and the read count is increased.
/routes/publicRoutes.js
const express = require('express')
const publicRouter = express.Router()
const publicController= require('../controllers/publicController')
publicRouter.get('/article/publish/:id', publicController.getPublishedArticle)
module.exports = publicRouter
Route ==> /api/article/publish/:id
/app.js
const publicRouter = require('./routes/publicRoute')
app.use('/api', publicRouter)
Conclusion.
In this article, we discussed how unauthenticated users can access some routes in the application.
Thanks for reading to the end.