Search code examples
node.jstemplatesexpressswig-template

How to make query results accessible from all pages


I am trying to be able to pass a variable through to my template, I can get it to work for single pages but I need to find a way to access the results of it in any page. Reason being that it is needed for my sidebar that is part a a template.

My template is

include header

include sidebar

content

include footer

That is just sudo code and clearly not my actual code.

The query I need to include is:

Item.count({"author.id":req.user.id}, (err, itemCount)=>{
 if(err){
  console.log(err);
 } else {
  var Count = JSON.stringify(itemCount);
  // somehow I need to store Count to be accessible inside my sidebar
 }
});

I know that I could take and put the query inside each and every route but is there a way I can do it for only the logged in user and put it in a middleware or something or the sort?

I currently have it stored in each route but I know that it is not DRY code and that updating it will be a HUGE pain since I have over 50 routes I handle.

My typical route is:

// dashboard
  app.get('/dashboard',
    setRender('dashboard/index'),
    setRedirect({auth: '/login'}),
    isAuthenticated,
    (req, res, next) => {

    },
    dashboard.getDefault);

Solution

  • You can use middleware for that purpose, i.e.:

    app.use('*', (req, res, next) => {
        Item.count({"author.id":req.user.id}, (err, itemCount)=>{
           if(err){
               console.log(err);
               res.status(500).send(err);
           } else {
              req.Count = JSON.stringify(itemCount);
              next();
           }
        });    
    });
    

    That will execute your query in all routes and save the result in req.Count. If you want that to execute only in a certain set of routes, modify the '*' portion for any path you'd like to match. Also, you may want to extract your other middleware functions like isAuthenticated into their own app.use clauses so that you can manage the order more accurately.