Sunday, 19 March 2017

Throw error if exported module function is called twice

I have a Node.js module that exports a function:

module.exports = function(data){

   return {
     // return some object
    }

};

I am looking to use a singleton pattern here, but without much extra fuss. This is for a library, and it's possible that my library code might call this function more than once by accident, but I need to rely on the user to define the code, so I can't guarantee that they will implement a proper singleton pattern.

Is there a good pattern I could use to throw an error if the exported function is called more than once?

I am thinking something like this:

const fn = require('./my-module');
const someObject = fn();
// next I want to somehow mark this module as having been loaded

To be explicit, the following is not good:

var loaded = null;

module.exports = function(data){

  if(loaded) {
    return loaded;
  }

  // do some stuff

  return loaded = {
    // return some object
  }

};

for some use cases that might suffice, but I am looking to do away with the standard singleton code for several reasons.

I don't think monkeypatching the require function will help with this but maybe.



via Alexander Mills

No comments:

Post a Comment