to-locals

0.1.2 • Public • Published

to-locals: res.locals-middleware

Transform callback-functions into connect middlewares, dumping their content to res.locals.

How

npm i to-locals

var toLocals = require('to-locals');
 
// toLocals([context], function, [arguments], key)
 
toLocals(getUsers, 'users');
toLocals(getUserById, [ 'req.params.id' ], 'user');
toLocals(users, users.find, 'user');
toLocals(users, 'find', 'users');
toLocals(users, 'findById', [ 'req.params.id' ], 'user');

What

Most node function are something like this:

var getUser = function(cb) {
    cb(null, 'user');
};

Writing your site with express, you usually call these functions and just put their values in res.locals:

app.get('/user', function(req, res) {
    getUser(function(err, user) {
        res.render('index', {
            user: user
        });
    });
});

With to-locals, it's a bit simpler:

app.get('/', toLocals(getUser, 'user'), function(req, res) {
    res.render('index');
});

It's perfect for mongoose:

var users = toLocals(mongoose.model('users'), 'find', 'users');
app.get('users', users, [...]);

For more complicate cases you can to-locals around an anonymous function:

var project = toLocals(function (cb) {
    mongoose.model('projects').findById(cb.req.query.id, cb);
}, 'project');

Notice how req (and res) was attached to the callback!

Or use to-locals's sugar:

var project = toLocals(mongoose.model('projects'), 'findById', [ 'req.query.id' ], 'project');

Tests

Mocha with some npm test.

Licence

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i to-locals

Weekly Downloads

3

Version

0.1.2

License

MIT

Last publish

Collaborators

  • eyy