Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding transparent decompression if content-encoding is set #149

Merged
merged 2 commits into from
Nov 19, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions lib/adapters/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var transformData = require('./../helpers/transformData');
var http = require('http');
var https = require('https');
var url = require('url');
var zlib = require('zlib');
var pkg = require('./../../package.json');
var Buffer = require('buffer').Buffer;

Expand Down Expand Up @@ -59,12 +60,27 @@ module.exports = function httpAdapter(resolve, reject, config) {
// Create the request
var transport = parsed.protocol === 'https:' ? https : http;
var req = transport.request(options, function (res) {

// uncompress the response body transparently if required
var stream = res;
switch(res.headers['content-encoding']) {
case 'gzip':
case 'compress':
case 'deflate': {
// add the unzipper to the body stream processing pipeline
stream = stream.pipe(zlib.createUnzip());

// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
}
}

var responseBuffer = [];
res.on('data', function (chunk) {
stream.on('data', function (chunk) {
responseBuffer.push(chunk);
});

res.on('end', function () {
stream.on('end', function () {
var data = Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') {
data = data.toString('utf8');
Expand Down
24 changes: 24 additions & 0 deletions test/unit/adapters/http.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var axios = require('../../../index');
var http = require('http');
var zlib = require('zlib');
var server;

module.exports = {
Expand Down Expand Up @@ -27,6 +28,29 @@ module.exports = {
});
},

testTransparentGunzip: function (test) {
var data = {
firstName: 'Fred',
lastName: 'Flintstone',
emailAddr: 'fred@example.com'
};

zlib.gzip(JSON.stringify(data), function(err, zipped) {

server = http.createServer(function (req, res) {
res.setHeader('Content-Type', 'application/json;charset=utf-8');
res.setHeader('Content-Encoding', 'gzip');
res.end(zipped);
}).listen(4444, function () {
axios.get('http://localhost:4444/').then(function (res) {
test.deepEqual(res.data, data);
test.done();
});
});

});
},

testUTF8: function (test) {
var str = Array(100000).join('ж');

Expand Down