I am newbie in ExpressJs and module pattern in my project. Now, i am stuck that how to use created controller function in another controller. Please look at example :-
menu.ctrl.js ------------ module.exports.save=function(req,res,next){ //here some logic //somethings like validate req.body,etc menu.save(function(err){ if(err) return next(err); res.json({msg:'menu save'}) }) } user.ctrl.js ------------ var user=require('./user.model') var menuCtrl=require('./menu.ctrl') module.exports.save=function(req,res,next){ //here some logic user.save(function(err){ if(err) return next(err); //HERE I WANT TO USE `menuCtrl.save()` function res.json({msg:'success'}); }) }
1 Answers
Answers 1
Decoupling your controller logic from your model logic will allow you reuse logic and make your application easier to maintain.
The idea is that controllers' purpose is to format input and output to and from you application, while models handle actual data manipulation. (This is a typical Rails-like MVC pattern for REST APIs)
To your example:
menuController.js
var menuModel = require('./menuModel'); module.exports.save = function(req, res, next) { menuModel.save(req.body, function(err) { if(err) return next(err); res.json({msg:'menu save'}) }); };
menuModel.js
module.exports.save = function(body, callback) { // Save menu to the DB menu.save(body, callback); };
userController.js
var userModel = require('./userModel'); module.exports.save = function(req, res, next) { userModel .save(function(err){ if(err) return next(err); res.json({msg:'success'}); }); }
userModel.js
var menuModel = require('./menuModel'); module.exports.save = function(body, callback) { // Save user to the DB user.save(body, function(err, res) { if (err) return callback(err); menuModel.save(body, callback); }); };
Rule of thumb, keep as less business logic as possible in controllers.
0 comments:
Post a Comment