How to selectively invoke middleware?

I have this menu on every page of my Node website:

enter image description here

I fill it out on a per request basis with a custom custom middleware:

app.use(function(req, res, next) {
  // find the 9 most popular technologies to show in the 'technologies' menu 
  // drop-down. this data is needed on every page, hence the middleware.
  var query = 
    'select \
       t.technologyName, \
       count(*) as count \
     from technologies t \
     join technology_video_map m \
       on m.technologyName = t.technologyName \
     where t.technologyName in ( \
       select technologyName \
       from technology_video_map m \
       join videos v \
         on m.videoId = v.videoId \
       where v.approved = 1) \
     group by t.technologyName \
     order by count desc, t.technologyName desc \
     limit 9';
  connection.query(query, function(err, technologies) {
    if (technologies.length === 9) {
      // 'Other' is a special technology
      technologies.push({ technologyName:'Other' });
    }
    res.locals.technologies = technologies;
    next();
  });
});

      

However, I have routes that return Json that, when called, call this middleware. This causes redundant calls to the database. How can I only reference this intermediate product when the view is returned?

// yes, invoke the middleware here!
router.get('/about', function(req, res) {
  res.render('about');
});

// no, don't invoke the middleware here, we don't have a view!
router.get('/autocomplete', function(req, res) {
  res.send({ options: new [] });
});

      

(I also try to cache this information, but I'll ask another question on how to cache with node-mysql

.)

+3


source to share


1 answer


You can tell the router that it only references middleware on certain routes, as described in the Express documentation here

// will be invoked on every call to /about
router.use('/about', function(req, res, next) {
  console.log('I\m such a middleware');
  next();
});

// will be invoked on every call to /json/...
router.use('/json/:somejson', function(req, res, next) {
  console.log('json comin..');
  next();
});

// yes, invoke the middleware here!
router.get('/about', function(req, res) {
  res.render('about');
});

// no, don't invoke the middleware here, we don't have a view!
router.get('/json/autocomplete', function(req, res) {
  res.send({ options: new [] });
});

      



I would strip my routes and name the db middleware only when calling `/ view / .. ', eg ..

0


source







All Articles