Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

merge getStream and postStream handlers into one function

  • Loading branch information...
commit c7f0323e859e27fe0314c044ce63fa85e00cbf3c 1 parent cf14586
@impronunciable authored
Showing with 16 additions and 50 deletions.
  1. +16 −50 lib/request.js
View
66 lib/request.js
@@ -93,51 +93,7 @@ Tuiter.prototype.getStream = function(url, params, callback){
var stream = new Stream();
var req = this.oa.get(url + '?' + qs.stringify(params), this.oa.access_token_key, this.oa.access_token_secret);
- var buf = '';
-
- req.on('response', function(res){
- res.setEncoding('utf-8');
-
- callback(stream);
-
- checkResStatus(res.statusCode, stream);
-
- res.on('data', function(chunk){
- buf += chunk;
- if(buf.indexOf('\r') !== -1){
- buf = buf.slice(0, buf.length - 2);
- var arr_buf = buf.split('\r\n');
- try{
- arr_buf.forEach(function(elem){
- var json_stream = JSON.parse(elem);
- if(json_stream.delete)
- stream.emit('delete', json_stream);
- else
- stream.emit('tweet', json_stream);
- });
- } catch(e){
- stream.emit('error', e);
- }
- buf = '';
- }
- });
-
- res.on('end', function(){
- stream.destroy();
- delete stream;
- });
-
- stream.on('end', function(){
- res.end();
- });
-
- });
- req.end();
-
- req.on('error', function(err){
- callback(stream);
- stream.emit('error', err);
- });
+ handleStream(req, stream, callback);
return this;
};
@@ -153,12 +109,18 @@ Tuiter.prototype.getStream = function(url, params, callback){
Tuiter.prototype.postStream = function(url, params, callback){
var stream = new Stream();
var req = this.oa.post(url, this.oa.access_token_key, this.oa.access_token_secret, params);
+ handleStream(req, stream, callback);
+
+ return this;
+};
+
+var handleStream = function(req, stream, callback){
var buf = '';
req.on('response', function(res){
res.setEncoding('utf-8');
- callback(stream);
+ callback(stream);
checkResStatus(res.statusCode, stream);
@@ -183,18 +145,22 @@ Tuiter.prototype.postStream = function(url, params, callback){
});
res.on('end', function(){
+ stream.destroy();
delete stream;
});
+ stream.on('end', function(){
+ res.end();
+ });
+
});
+ req.end();
req.on('error', function(err){
callback(stream);
stream.emit('error', err);
});
- req.end();
-
- return this;
+
};
/*
@@ -204,7 +170,7 @@ Tuiter.prototype.postStream = function(url, params, callback){
* @param {Object} stream
*/
-function checkResStatus(status, stream){
+var checkResStatus = function(status, stream){
if(status >= 400){
if(config.error[status]){
stream.emit('error',{code: status, definition: config.error[status].definition, description: config.error[status].description});
Please sign in to comment.
Something went wrong with that request. Please try again.