Default options for NodeJS, NPM, and CommonJS modules
Defaultable is a simple drop-in tool to make your Node API very convenient for your users. It comes from internal Iris Couch tooling.
Defaultable is pure CommonJS Javascript, and is also available as an NPM module.
$ npm install defaultable
Is it any good?
Yes.
What your users see
With Defaultable, these are the promises you make to your users (in documentation, presentations, etc.)
Dear users, just require my code and use it like normal.
var api = ; api; // Process Bob.api; // Process Eve.
If you are using the same options a lot, set them as defaults.
var api = ; api; // minimum will be 5api; // minimum is still 5
Defaults can even inherit from other defaults.
var api = ; var fivers = api;var rich = fivers;var poor = fivers; poor; // dollars will be 10, minimum will be 5rich; // dollars will be 800, minimum is still 5
What you see
Defaulable wraps a CommonJS module.
Your original code:
// my_mod.js // My code basically starts herevar DEFAULTS = "minimum":0 "dollars":0 ; exports { opts = opts || {}; console; console; console;}// And obviously it ends here.
Your new code:
// my_mod.js // Insert these lines at the top...module "minimum": 0 "dollars": 0 { // The rest of your code follows unchanged. // My code basically starts here (pretty much unmodified, but no hard-coded DEFAULTS)exports { opts = opts || {}; console; console; console;}// Code ends here, just one more thing to append... } // defaultable
How it works
It's really simple.
Defaultable passes the initial defaults to you as DEFAULTS
. Use module
, module.exports
, or exports
as usual to build your module API.
Your API gets an additional .defaults()
function, which will re-evaluate your code with new user-provided defaults.
Automatic defaults in require()
If you have multiple related modules, it can be nice for them to share defaults.
// main.jsmodule "minimum": 0 "dollars": 0 { var submod = ; // Bad! }
For this situation, defaultable provides a wrapped require()
function. It works just like before, however if the modules you load is itself defaultable, it will be initialized with the current defaults.
// main.jsmodule "minimum": 0 "dollars": 0 { var submod = ; // Good! Notice the "require" parameter above. var legacy_mod = ; // Still works.var http = ; // Still works. }
If you do not want your module to inherit anything implicitly, use Defaultable's .def()
function instead. This is useful for top-level modules of packages, for example.
// main.js -- The "main" file in package.json