connect-locals
v1.0.0
Published
Connect middleware which appends a locals object for scoped request variables.
Downloads
7
Maintainers
Readme
Locals
Connect/Express middleware which appends a locals object for scoped request variables.
Installation
$ npm install connect-locals
Usage
var locals = require( 'connect-locals' );
locals( request, response, next )
Connect/Express middleware which appends a locals object
for scoped request variables.
var app = require( 'express' )();
app.use( before );
app.use( locals );
app.use( after );
function before( req, res, next ) {
console.log( req.locals );
// returns undefined
next();
}
function after( req, res, next ) {
// Append data to the `locals` object...
req.locals.data = 'beep';
next();
}
Notes
If a
request
object already has a definedlocals
property, the middleware does not overwrite the existing value.The intent of the
locals
object is similar to Express' res.locals, except the latter is primarily for populating view templates. This module helps avoid possible collisions and separate concerns.To ensure that the
locals
object is available to all subsequent middleware, mount the middleware at the top of the middleware stack.var app = require( 'express' )(); app.use( locals ); app.use( logger ); app.get( '/', main ); app.get( '/foo', foo ); app.get( '/bar', bar );
Examples
var express = require( 'express' ),
request = require( 'request' ),
locals = require( 'connect-locals' );
function db( req, res, next ) {
process.nextTick( onTick );
function onTick() {
req.locals.data = 'beep';
next();
}
}
function transform( req, res, next ) {
req.locals.data = req.locals.data.replace( /ee/, 'oo' );
next();
}
function send( req, res, next ) {
res.send( req.locals.data );
next();
}
function onListen() {
request({
'method': 'GET',
'uri': 'http://127.0.0.1:7331'
}, onResponse );
}
function onResponse( err, res, body ) {
if ( err ) {
throw err;
}
console.log( 'Response status: %s.', res.statusCode );
console.log( 'Response body: %s.', body );
process.exit( 0 );
}
var app = express();
app.use( locals );
app.get( '/', db, transform, send );
app.listen( 7331, onListen );
To run the example code from the top-level application directory,
$ node ./examples/index.js
Tests
Unit
Unit tests use the Mocha test framework with Chai assertions. To run the tests, execute the following command in the top-level application directory:
$ make test
All new feature development should have corresponding unit tests to validate correct functionality.
Test Coverage
This repository uses Istanbul as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:
$ make test-cov
Istanbul creates a ./reports/coverage
directory. To access an HTML version of the report,
$ make view-cov
License
Copyright
Copyright © 2015. Athan Reines.