Skip to content

Instantly share code, notes, and snippets.

@bajtos
Created July 25, 2014 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bajtos/051ec6e12b027559635d to your computer and use it in GitHub Desktop.
Save bajtos/051ec6e12b027559635d to your computer and use it in GitHub Desktop.
Test for how strong-remoting handles request pause/resume
var net = require('net');
var extend = require('util')._extend;
var express = require('express');
var RemoteObjects = require('strong-remoting');
var objects = RemoteObjects.create();
var reqUrl = givenStreamingEchoMethodWithAsyncSharedCtor();
var app = express();
// Simulate the situation when somebody resumed
// the request before are remoted function was called
// Disable this middleware to make the test pass
app.use(function(req, res, next) {
req.resume();
next();
});
app.use(objects.handler('rest'));
app.listen(0, function() {
this.unref();
sendHttpRequestInOnePacket(
this.address().port,
'POST ' + reqUrl + ' HTTP/1.0\n' +
'Content-Length: 1\n' +
'Content-Type: application/x-custom-octet-stream\n' +
'\n' +
'X',
function(err, response) {
if (err) throw err;
console.log('--response--\n', response, '\n--end--\n');
console.log(/\nX$/.test(response) ? 'PASSED' : 'FAILED');
}
);
});
//-- HELPERS --
function givenStreamingEchoMethodWithAsyncSharedCtor() {
function Test() {
}
extend(Test, {
shared: true,
http: { 'path': '/test' }
});
Test.sharedCtor = function(id, cb) {
process.nextTick(function() {
cb(null, new Test());
});
};
extend(Test.sharedCtor, {
shared: true,
accepts: [ { arg: 'id', type: 'any', http: { source: 'path' }}],
http: { path: '/:id' },
returns: { root: true }
});
Test.prototype.method = function(req, res, cb) {
var body = new Buffer(0);
req.on('data', function(chunk) {
console.log('data', chunk);
body += chunk;
});
req.on('end', function() {
res.end(body.toString());
// we must not call the callback here
// because it will attempt to add response headers
});
req.once('error', function(err) {
cb(err);
});
};
extend(Test.prototype.method, {
shared: true,
http: { method: 'post' },
accepts: [
{ arg: 'req', type: 'Object', http: { source: 'req' } },
{ arg: 'res', type: 'Object', http: { source: 'res' } }
]
});
objects.exports.test = Test;
return '/test/1/method';
}
function sendHttpRequestInOnePacket(port, reqString, cb) {
var socket = net.createConnection(port);
var response = new Buffer(0);
socket.on('data', function(chunk) {
response += chunk;
});
socket.on('end', function() {
callCb(null, response.toString());
});
socket.once('error', function(err) {
callCb(err);
});
socket.write(reqString.replace(/\n/g, '\r\n'), 'utf-8');
function callCb(err, res) {
if (!cb) return;
cb(err, res);
cb = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment