How to make reusable function code in Expressjs?

I am new to ExpressJs and the module in my project. Now I'm stuck with how to use the created controller function in another controller. See an 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'}); }) } 
+5
source share
2 answers

Decoupling the logic of the controller with the logic of the model will allow you to reuse the logic and simplify its work.

The idea is that the goal of the controllers is to format input and output to and from your application, while models handle actual data manipulations. (This is a typical Rails-like MVC pattern for the REST API)

For 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 little logic as possible in controllers.

+5
source
 //Here is a solution if you are using same route file // var getNotificationSetting = async function (user_id) { let params = {} params = await NotifcationSetting.findAll({ where: { ns_user_id : user_id }, }); return params; } //now calling in action router.get('/', async function(req, res, next) { let params = {} //for setting section params = await getNotificationSetting(req.session.user.user_id); }); 
0
source

Source: https://habr.com/ru/post/1264843/


All Articles