Last active
September 16, 2016 11:47
-
-
Save geowa4/9256363 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.
This file contains hidden or 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
'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