How to make module configuration available correctly?

4

I'm creating a Node.js module and wanted to make use settings available. Let's say I wanted to provide a prefix for console.log just as an example:

let opcoes = {};

function imprimir(texto) {
  console.log(opcoes.prefixo, texto);
}

module.exports = ({
  prefixo = 'padrao'
} = {}) => {
  opcoes = {
    prefixo
  };

  return { imprimir };
};

In case the above module call would look something like this:

const { imprimir } = require('modulo')({ prefixo: 'prefixo' });

imprimir('teste');

The output above will be as follows:

  

test prefix

But I wish this setting could only be done once in use by overwriting the default. For example, make the above call in modulo1 of my system and the call below in modulo2 :

const { imprimir } = require('modulo')();

imprimir('teste');

I would like the result to be:

  

test prefix

And not as (That's what happens today):

  

undefined test

And neither:

  

default test

What would happen with minor modifications.

Contextualizing:

I have a module that makes the call to a service via HTTP , but sometimes the service version is updated and I want to allow anyone who is consuming the module to perform this update without having to wait for me to update the link of the version. But this setting is only needed once and not at every service call.

Note: I'm using the Airbnb Style Guide and would like to continue in this pattern.

    
asked by anonymous 06.08.2018 / 15:52

1 answer

1

I solved by assigning values in the variable itself and checking for the fill in the configuration function:

let opcoes = {
  prefixo: 'padrao'
};

function imprimir(texto) {
  console.log(opcoes.prefixo, texto);
}

module.exports = ({
  prefixo
} = {}) => {
  opcoes = {
    prefixo: prefixo || opcoes.prefixo
  };

  return { imprimir };
};
    
11.08.2018 / 21:08