I am beginner in node.js development and i encountered a problem. I want to build web API (for browser) and mobile API (for example, for android).
F.e. i have middleware:
var User = require('../model/user');
module.exports = function (req, res, next) {
if (req.headers) {
var app = req.headers['app'];
if (app === 'mobile') {
req.mobile = true;
return next();
}
}
req.mobile = false;
if (!req.session || !req.session.user) return next();
User.findById(req.session.user._id, function (err, user) {
if (err) return next(err);
req.user = res.locals.user = user;
next();
});
};
I check header is current request from mobile application.
Common private function for login:
var commonLogin = function (email, password, callback) {
var validationError = checkCredentials(email, password);
if (validationError) {
return callback(validationError, null);
} else {
user.findOne({email: email}, function (err, user) {
if (err) {
return callback(error.serverInternalError(), null);
} else if (!user) {
return callback(error.userNotFound(), null);
} else {
return callback(null, user);
}
});
}
};
And call:
exports.login = function (req, res) {
var isMobile = req.mobile;
var email = req.body.email;
var password = req.body.password;
commonLogin(email, password, function(error, user) {
if (error) {
if (isMobile) {
return res.send(error);
} else {
req.flash('message', error.error.message);
return res.redirect('/auth/login');
}
//Other conditions
How i can simplify different replies for Web API and mobile API? In this approach, code is dirty and big. Thanks.