Question3r
Question3r

Reputation: 3752

pass module parameters from controller to model in NodeJs

I use the MVC pattern for my NodeJs application.

I have a module called logger, it's a customized console.log function and I want to access this module in all other modules because I want to log information everywhere.

So my server.js requires the logger module. Then it passes this parameter to the controller.

const model = require('./model');

module.exports = function(app, logger){

app.get('/', function (req, res) {
    res.render('main', model.funcOne());
});

};

So I want my model having this logger variable.

module.exports = {
  funcOne: function(){
    logger.log("msg"); // missing module
    return {
//
    };
  },

  funcTwo: function(){
    logger.log("msg"); // missing module
    return {
//
    };
  }
};

Some possibilities:

Are there any better / cleaner ways?

Upvotes: 1

Views: 993

Answers (1)

The Reason
The Reason

Reputation: 7973

I'm not sure if it is what are you looking for, but anyway I'll try to help. You can have a high order function which will wrap your functions with your logger. So how it works - say you want to log every functions you created. But you dont want to refactor all of them and add console.log() // as example to all of them. So you created a withLogger high order function, like below:

const withLogger = (f) => (...params) => {
  console.log('logger')
  return f(...params)
}  

It takes a function as a input parameter what do you want to log, and returns "same" function with injected console.log() in it. It works because of closure, i hope you are familiar with it. So here is an example:

const multiply = (x, y) => x * y

const multiplyWithLogger = withLogger(multiply)
const result = multiplyWithLogger(3, 4); // console.log('logger') at this point
console.log(result) // 12

You can do same thing with your module, but with more additional steps.

// withLogger.js
const logger = require('./mylogger');

const withLogger = (f) => (...params) => {
  logger.log('msg')
  return f(...params)
}

module.export = withLogger;

// your module
const withLogger = require('./withLogger');

module.export = {
  fncOne: withLogger(() => { //do some stuff you want })
  fncTwo: withLogger(() => { //do some stuff you want })
}

So every time you call fncOne or fncTwo you it will log msg.

Hope it make sense.

Upvotes: 1

Related Questions