I want to implement a function in async. This code is for authentication, that if user is logged in, than can't reach the page without login. My code in app.js file worked, there is the isLoggedOut
function, where i can implement, so this code is working, but I want to copy this code to my controller.js.
The working code in app.js:
app.get('/explore-random', isLoggedIn, (req, res) => {
const count = Recipe.find().countDocuments();
const random = Math.floor(Math.random() * count);
const recipe = Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
})
The controller.js, where i want to implement isLoggedOut
function to exploreRandom
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
function isLoggedOut(req, res, next) {
if (!req.isAuthenticated()) return next();
res.redirect('/home');
}
/**
* GET /explore-random
* Explore Random
*/
exports.exploreRandom = async (req, res) => {
try {
let count = await Recipe.find().countDocuments();
let random = Math.floor(Math.random() * count);
let recipe = await Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
} catch (error) {
res.status(500).send({message: error.message || "Error Occured"});
}
}
CodePudding user response:
You can simply pass the exported exploreRandom
function as a handler to your app.get
route:
const exploreRandom = require('./path/to/explore-random-module');
app.get('/explore-random', isLoggedIn, exploreRandom);