middleware-bind

1.0.0 • Public • Published

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(req, next) ->
    # 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'(req, next) -> asyncMethod next

name can be nested.

# will bind the result of asyncMethod to `req.loaded.foo.bar` 
bind 'foo.bar'(req, next) -> 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

router.get '/user',
    bind 'users.all'(req, next) -> dao.user.all next
    (req, res, next) ->
        console.log 'loaded users'req.loaded.users.all
        # will output the result of `dao.user.all` 
        next()
    render view.user.all
 
router.get '/user/:id',
    bind 'user.object'(req, next) -> dao.user.byId req.params.idnext
    render view.user.show

Credits

bind was developed with snd during a project. The initial idea was from snd. I refactored the library and provided unit tests.

Readme

Keywords

none

Package Sidebar

Install

npm i middleware-bind

Weekly Downloads

1

Version

1.0.0

License

none

Last publish

Collaborators

  • mren