Tommy V
Tommy V

Reputation: 177

Overriding method in node.js

i'm looking for the best way to overrid a method in a custom module node.js.

I'm working on a custom middleware who will help me to automatically load some custom module. Like security, users etc...

But i want to be able to override some methods if i need something like a custom security hand check. For now the only way i found is to export a function who will replace my method and expose context variables.

// CUSTOM MODULE EXAMPLE
// ========================================

var myVar = "Hello ";
var myVar2 = "!";

var method = function() {
  return "world" + myVar2;
}

module.exports.loadModule = function() {
   console.log(myVar + method());
};

module.exports.overrideMethod = function(customMethod) {
  method = customMethod;
};

module.exports.myVar2 = myVar2;

And my main app will be like that:

// MAIN APP EXAMPLE
// ========================================

var myCustomModule = require('customModule.js');

myCustomModule.overrideMethod(function() {
   return "viewer" + myCustomModule.myVar2;
});

myCustomModule.loadModule(); 

What do you think? Am i on the good way?

Thanks for reading. Tom

Upvotes: 1

Views: 7417

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

Generally I treat any module that has mutable global state like this to be a mistake. Instead, I'd opt for creating an object with these methods and having a way to pass in overrides.

// CUSTOM MODULE EXAMPLE
// ========================================

var DEFAULT_PREFIX = "Hello ";
var DEFAULT_SUFFIX = "!";


var DEFAULT_METHOD = function() {
  return "world" + DEFAULT_SUFFIX;
};

module.exports = function(options){
    var method = options.method || DEFAULT_METHOD

    return {
        loadModule: function(){
            console.log(myVar + method());
        }
    };
};

module.exports.DEFAULT_SUFFIX = DEFAULT_SUFFIX;

Then you can use this like this:

// MAIN APP EXAMPLE
// ========================================

var myCustomModule = require('customModule.js');

var loader = myCustomModule({
    method: function() {
        return "viewer" + myCustomModule.DEFAULT_SUFFIX;
    }
});

loader.loadModule(); 

Upvotes: 1

Related Questions