Reputation: 75824
I am looking for a good way to setup configuration for an npm module I'm working on.
The module has two functions notify.sms.send()
and notify.email.send()
. I'm also providing a third abstract function that calls both (or whichever are enabled) called notify.send()
.
I have an object called notify.cfg
which is just a simple object hash {}
.
I'm wondering if this is a good way to do this. Because its a module, I can't hardcode anything and configuration should be passed in when the module is required....like this:
//setup smtp server
var smtp = {
host: xxx,
user: user,
pass: pass,
port: port
};
//setup email headers
var email = {
to: '[email protected]',
from: '[email protected]'
};
var notify = require('app-notify');
//set your configuration
notify.cfg.email = email;
notify.cfg.smtp = smtp;
The signature of notify.cfg
is this:
var cfg = {};
exports.cfg = cfg;
I'm running into some issues while testing where when I overwrite the notify.cfg = myConfig
in my beforeEach
tests it seems to still retain older data from previous tests that have run. I don't know if its this config setup for my module or the way I'm writing my tests.
For anyone interested the code is here: https://github.com/chovy/app-notify
Upvotes: 0
Views: 200
Reputation: 13570
You are effectively making configuration singleton thus package becomes less usable. A typical API looks like:
var Notify = require('app-notify');
var notify = new Notify({
email : ...
smtp : ...
});
If a user wants a singleton notify
object they can just module.exports = new Notify({...})
and require it elsewhere.
Your index.js
file would look like this:
function Notify(config) {
if (!(this instanceof Notify))
return new Notify(config);
....
}
module.exports = Notify;
instanceof
check is used to make it possible to omit new
keyword.
Upvotes: 1