Param Injection
(Node.js) Wraps a function so that one or some of the parameters can be auto-loaded at run time. Mainly used to build modules or functions that may have some run time dependencies.
This is similar to "Dependency Injection" but much simpler.
What
It exports a function.
var injectify = ;
And that can be used to wrap a function, so that one or some of the parameters of the function can be actively retrieved (with a given getter) at run time.
For example, say you have a function that does something, and requires some arguments.
var request = ;var Promise = ; { return { ; }}
And one of the arguments can be from another function (or say you want to build it with another function).
{ return { ; };}
Now instead of calling them together all the time, you can wrap the original function and you get a new function.
var myRequest = ;
And inject the getter function.
myRequest;
Tip: you can do the above 2 lines in one step.
var myRequest = ;
Now you can run the wrapper, with only the other arguments (meaning that the new function has a different API with the original function).
;
Why
This small tool solves a very specific problem, where:
- You are building a module (not an application where you could do whatever you want).
- And you are building a function that has some asynchronous dependencies.
- And you want to give it a default parameter while still give your user a chance to change it.
Without this tool it is usually hard to achieve the same thing but with this tool the code can be a bit more complex; your choice.
API
TODO
Variants
Return self
A variant that returns the context or this
.
Can be used to build some callback based APIs.
However note that the dependencies are still promise based.
Return auto
A variant that returns either the promise or the context, depending on if a callback function is given.
Can be used to build something with both a promise API and a callback API.
However note that 1) the dependencies are still promise based and 2) the last argument is considered as a callback if it is a function and 3) we assume the callback will be properly handled.
Cached result (caching the promise)
TODO
Bonus
As a flow control tool
TODO