0

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

1
  • The implementation looks fine, what is the problem? Commented Dec 16, 2021 at 13:17

1 Answer 1

1

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.