Created
September 15, 2011 19:59
-
-
Save travisperson/1220305 to your computer and use it in GitHub Desktop.
"Resthook"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Hook = require('hook.io').Hook, | |
http = require('http'), | |
util = require('util'), | |
uuid = require('node-uuid'), | |
url = require('url'), | |
qstring = require('querystring'); | |
var Resthook = exports.Resthook = function(options){ | |
var self = this; | |
Hook.call(self, options); | |
self.on('hook::ready', function(){ | |
self._startHTTPServer(); | |
}); | |
}; | |
// Resthook inherits from Hook | |
util.inherits(Resthook, Hook); | |
var _sessions = {}; | |
Resthook.prototype._startHTTPServer = function(){ | |
var self = this; | |
http.createServer(function(req, res){ | |
var request = url.parse(req.url) | |
var params = qstring.parse(request.query); | |
var _path = cleanpath(request.pathname); | |
var body = ''; | |
// | |
// Buffer up all the body data from incoming request | |
// | |
req.on('data', function(data){ | |
body += data; | |
}); | |
// | |
// On the end of the request, emit a hook.io message with HTTP payload | |
// | |
req.on('end', function(){ | |
var _uuid = uuid(); | |
_sessions[_uuid] = res; | |
// Auto timeout after self.timeout. | |
setTimeout(function () { | |
if(!res.finished) { | |
res.end(JSON.stringify({ | |
: 'Timeout' | |
})); | |
self.log(self.name, 'session timeout', _uuid); | |
delete _sessions[_uuid]; | |
} | |
}, self.timeout); | |
// If its json lets convert it so its a little nicer | |
try { | |
var json = JSON.parse(body); | |
} | |
catch(err) { | |
var json = body; | |
} | |
return self.emit(_path.join('::'), {'request': _path, 'method': req.method, 'post':json, 'query': params, '_session': _uuid}); | |
}); | |
}).listen(self.port); | |
// We have a response! | |
// Look up the id and send the response back | |
self.on('*::gotResponse', function (data) { | |
_sessions[data._session].end(JSON.stringify(data)); | |
delete _sessions[data._session]; | |
}); | |
self.log(self.name, 'http server started', self.port); | |
}; | |
function cleanpath(_path) { | |
if(_path) { | |
if(_path.charAt(0) == '/') | |
_path = _path.substr(1); | |
if(_path.charAt(_path.length - 1) == '/') | |
_path = _path.substr(0,_path.length - 1); | |
_path = _path.split('/'); | |
} | |
return _path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment