node.js - How to selectively invoke middleware? -


i have menu on every page in node website:

enter image description here

i populate on each request using custom middleware:

app.use(function(req, res, next) {   // find 9 popular technologies show in 'technologies' menu    // drop-down. data needed on every page, hence middleware.   var query =      'select \        t.technologyname, \        count(*) count \      technologies t \      join technology_video_map m \        on m.technologyname = t.technologyname \      t.technologyname in ( \        select technologyname \        technology_video_map m \        join videos v \          on m.videoid = v.videoid \        v.approved = 1) \      group t.technologyname \      order count desc, t.technologyname desc \      limit 9';   connection.query(query, function(err, technologies) {     if (technologies.length === 9) {       // 'other' special technology       technologies.push({ technologyname:'other' });     }     res.locals.technologies = technologies;     next();   }); }); 

however, have routes return json that, when invoked, invoke middle-ware. inducing superfluous database calls. how can invoke middle-ware when view returned?

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

(i keen cache information, ask question how cache using node-mysql.)

you can tell router invoke middleware on specific routes described in express documentation here

// invoked on every call /about router.use('/about', function(req, res, next) {   console.log('i\m such middleware');   next(); });  // invoked on every call /json/... router.use('/json/:somejson', function(req, res, next) {   console.log('json comin..');   next(); });  // yes, invoke middleware here! router.get('/about', function(req, res) {   res.render('about'); });  // no, don't invoke middleware here, don't have view! router.get('/json/autocomplete', function(req, res) {   res.send({ options: new [] }); }); 

i'd go segmenting routes , calling db middleware on calls `/view/..', example..


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -