Skip to content

Instantly share code, notes, and snippets.

@jtbonhomme
Forked from geowa4/responseStream.js
Created September 16, 2016 11:47
Show Gist options
  • Save jtbonhomme/04a308c7438046a2a2189ed1c5a8a8a7 to your computer and use it in GitHub Desktop.
Save jtbonhomme/04a308c7438046a2a2189ed1c5a8a8a7 to your computer and use it in GitHub Desktop.
This Node Stream will transform a response stream from request (https://github.com/mikeal/request) to be an object containing the status code, headers, and body. The data is emitted as an error if the response is not a 2xx.
'use strict';
var Base, ResponseTransformStream, twoHundo;
Base = require('stream').Transform;
twoHundo = /^2\d\d$/;
ResponseTransformStream = function (opts) {
Base.call(this, opts);
this.headers = {};
this.body = '';
};
require('util').inherits(ResponseTransformStream, Base);
ResponseTransformStream.prototype.setHeader = function (key, value) {
this.headers[key] = value;
};
ResponseTransformStream.prototype._transform = function (chunk, enc, next) {
this.body += String(chunk);
next();
};
ResponseTransformStream.prototype._flush = function(next) {
var data;
data = {
statusCode: this.statusCode,
headers: this.headers,
body: JSON.parse(this.body)
};
if (twoHundo.test(this.statusCode)) {
this.push(JSON.stringify(data));
next();
}
else {
next(data);
}
};
module.exports = function responseTransform (opts) {
return new ResponseTransformStream(opts);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment