6

So I have a user view and an admin view that are very similar except that an admin view can upload new data to my web app which displays different charts; thus I want to use the same controller that gets the data from the database.

In the controller, I need it to either render my user view or my admin view, so how can I pass that as a variable from the route to tell the controller which view to render.

For example, I have the normal /users route which all it does is

//users

router.get('/', uploadController.get_detail);

For the /admin route, it needs to first make sure that the credentials are valid and then render the same controller but pass in a different variable. This is because in the controller is where I have the :

// uploadController

res.render('VIEW', { title: 'Test', data: results });

And VIEW is where I want the variable to go. So if it came from /users route, then it was sent a variable 'users' and that would render my users.pug view. Same with the /admin route which would render my admin.pug view.

Jose Varela
  • 145
  • 3
  • 12

1 Answers1

13

It looks like uploadController.get_detail() is a middleware function right? So it has a signature that looks like:

uploadController.get_detail(req, res, next)

right?

The way you will normally handle passing data to middleware is to put a variable on res.locals then the middleware can pick it up. For example:

router.get('/', 
    function(req, res, next){ 
       res.locals.admin = true
       next()
    },
    uploadController.get_detail
);

Then in get_detail() you can read it off the res object:

uploadController.get_detail(req, res, next) {
    if (res.locals.admin) {
      // do admin stuff
    }
}
Mark
  • 90,562
  • 7
  • 108
  • 148