Skip to content

Instantly share code, notes, and snippets.

@othiym23
Last active December 22, 2015 17:19
Show Gist options
  • Save othiym23/6505028 to your computer and use it in GitHub Desktop.
Save othiym23/6505028 to your computer and use it in GitHub Desktop.
Fixed & reduced version of https://gist.github.com/dazld/6493549
'use strict';
var assert = require('assert')
, director = require('director')
, EventEmitter = require('events').EventEmitter
, ns = require('continuation-local-storage').createNamespace('testing')
;
/*
* CONSTANTS
*/
var NUM_TESTS = 1000;
function createRouter() {
var emitter = new EventEmitter()
, router = new director.http.Router()
;
var createHandler = function () {
return function () {
assert(ns.get('req'), "req propagated to Router handler");
emitter.emit('routeMatched', ns.get('req').someId);
};
};
var ret = {
_createHandler : createHandler,
initialize : function () {
router.on('get','/page/:id', ret._createHandler(/* route, routeFunction */));
},
on : emitter.on.bind(emitter),
once : emitter.once.bind(emitter),
dispatch : function (req, res) {
assert(ns.get('req'), "req propagated to Router dispatch");
router.dispatch(req, res, function (err) {
console.log(err);
});
}
};
return ret;
}
var router = createRouter();
router.initialize();
function spawnAsync(i) {
var req = {
url : '/page/' + i,
method : 'get',
someId : Math.floor(Math.random() * Date.now()),
headers : {
'content-type' : 'text/html'
}
};
ns.set('req', req);
process.nextTick(router.dispatch.bind(router, req));
}
router.on('routeMatched', function (id) {
assert(id, "id passed to routeMatched listener");
assert(ns.get('req'), "req propagated to routeMatched listener");
assert.equal(id, ns.get('req').someId, "passed id and req.someId match");
});
// actually do the thing
for (var i = 0; i < NUM_TESTS; i++) ns.run(spawnAsync.bind(null, i));
{
"name": "clsbughunt",
"dependencies": {
"continuation-local-storage": "~2.1.2",
"director": "~1.2.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment