Skip to content

Commit 3baf979

Browse files
raphaeleidusmonkpow
authored andcommitted
do gzip and gunzip asynchronously (#406)
1 parent 03f6c03 commit 3baf979

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

app/steps/decorateUserRes.js

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,24 @@ function isResGzipped(res) {
1010

1111
function zipOrUnzip(method) {
1212
return function(rspData, res) {
13-
return (isResGzipped(res) && rspData.length) ? zlib[method](rspData) : rspData;
13+
return new Promise(function (resolve, reject) {
14+
if (isResGzipped(res) && rspData.length) {
15+
zlib[method](rspData, function(err, buffer) {
16+
if(err) {
17+
reject(err);
18+
} else {
19+
resolve(buffer);
20+
}
21+
});
22+
} else {
23+
resolve(rspData);
24+
}
25+
});
1426
};
1527
}
1628

17-
var maybeUnzipResponse = zipOrUnzip('gunzipSync');
18-
var maybeZipResponse = zipOrUnzip('gzipSync');
29+
var maybeUnzipPromise = zipOrUnzip('gunzip');
30+
var maybeZipPromise = zipOrUnzip('gzip');
1931

2032
function verifyBuffer(rspd, reject) {
2133
if (!Buffer.isBuffer(rspd)) {
@@ -40,25 +52,33 @@ function decorateProxyResBody(container) {
4052
return Promise.resolve(container);
4153
}
4254

43-
var proxyResData = maybeUnzipResponse(container.proxy.resData, container.proxy.res);
55+
var proxyResDataPromise = maybeUnzipPromise(container.proxy.resData, container.proxy.res);
4456
var proxyRes = container.proxy.res;
4557
var req = container.user.req;
4658
var res = container.user.res;
59+
var originalResData;
4760

4861
if (res.statusCode === 304) {
4962
debug('Skipping userResDecorator on response 304');
5063
return Promise.resolve(container);
5164
}
5265

53-
return Promise
54-
.resolve(resolverFn(proxyRes, proxyResData, req, res))
66+
return proxyResDataPromise
67+
.then(function(proxyResData){
68+
originalResData = proxyResData;
69+
return resolverFn(proxyRes, proxyResData, req, res);
70+
})
5571
.then(function(modifiedResData) {
5672
return new Promise(function(resolve, reject) {
5773
var rspd = as.buffer(modifiedResData, container.options);
5874
verifyBuffer(rspd, reject);
59-
updateHeaders(res, proxyResData, rspd, reject);
60-
container.proxy.resData = maybeZipResponse(rspd, container.proxy.res);
61-
resolve(container);
75+
updateHeaders(res, originalResData, rspd, reject);
76+
maybeZipPromise(rspd, container.proxy.res).then(function(buffer) {
77+
container.proxy.resData = buffer;
78+
resolve(container);
79+
}).catch(function(error){
80+
reject(error);
81+
});
6282
});
6383
});
6484
}

0 commit comments

Comments
 (0)