middleware-bind
Transforms an asynchronous function into a middleware.
The result of the function will be bound to request.loaded
.
Use this library if you want to load async data in a clean way.
Short Description
Transforms an asynchronous function f
into a middleware.
The middleware will call f
with (req, callback)
.
f
has to call callback
with err, value
which will cause value
to be bound to req.loaded[name]
.
Usage
bind name # do async stuff and call `next` when you are finished error = null result = 'result' next errorresult
name
is the directive where to save the results from function
.
# will bind the result of asnycMethod to `req.loaded.foo` bind 'foo' asyncMethod next
name
can be nested.
# will bind the result of asyncMethod to `req.loaded.foo.bar` bind 'foo.bar' asyncMethod next
If the asynchronous method returns an error the process is aborted and a Status Code of 500 is returned to the user.
Example
routerget '/user' bind 'users.all' daouserall next consolelog 'loaded users'reqloadedusersall # will output the result of `dao.user.all` next render viewuserall routerget '/user/:id' bind 'user.object' daouserbyId reqparamsidnext render viewusershow
Credits
bind
was developed with snd during a project.
The initial idea was from snd.
I refactored the library and provided unit tests.