I\'m using NodeJS and Express, I have the following route and the middleware function isMobile. If I don\'t use return next(); in the isMobile function, the app gets stuck becau
You have a couple of choices:
Attach the value to the req
object:
app.get('/', isMobile, function(req, res){
// Now in here req.phone is md.phone. You can use it:
req.phone.makePrankCall();
});
function isMobile(req, res, next) {
var MobileDetect = require('mobile-detect');
md = new MobileDetect(req.headers['user-agent']);
req.phone = md.phone();
next();// No need to return anything.
}
This is how many of express/connect middlewares pass values. Like bodyParser which attaches body property to request object, or session middleware which attaches session property to request object.
Though note that you have to be careful that no other library uses that property, so there's no conflicts.
Don't make it a middleware, just use the function directly. If it's not asynchronous like above, and not gonna be used globally for all routes(not gonna have something like this: app.use(isMobile)
), this also a good solution:
app.get('/', function(req, res){
var phone = isMobile(req);
phone.makePrankCall();
});
function isMobile(req) {
var MobileDetect = require('mobile-detect');
md = new MobileDetect(req.headers['user-agent']);
return md.phone();
}
If it's expensive to compute, and you might use it in more than one middleware you can cache it with a WeakMap(or use a module that does it for you):
app.get('/', function(req, res){
var phone = isMobile(req);
phone.makePrankCall();
});
var cache = new WeakMap()
function isMobile(req) {
var MobileDetect = require('mobile-detect');
result = cache.get(req);
if (result) {
return result;
} else {
md = new MobileDetect(req.headers['user-agent']).phone();
cache.set(req, md);
return md;
}
}