use async version for gzip and gunzip

This commit is contained in:
Damian Krzeminski 2017-04-12 19:51:53 -07:00
parent 07e03deedb
commit 84522e9d11

View file

@ -22,18 +22,30 @@ function isGzipped(data) {
return data[0] === 0x1f && data[1] === 0x8b; return data[0] === 0x1f && data[1] === 0x8b;
} }
function unzipTile(tile) { function unzip(tile, fn) {
if (tile.isGzipped) { if (!tile.isGzipped) {
tile.data = zlib.gunzipSync(tile.data); return fn();
}
zlib.gunzip(tile.data, function(err, buffer) {
if (!err) {
tile.data = buffer;
tile.isGzipped = false; tile.isGzipped = false;
} }
fn(err);
});
} }
function zipTile(tile) { function zip(tile, fn) {
if (!tile.isGzipped) { if (tile.isGzipped) {
tile.data = zlib.gzipSync(tile.data); return fn();
}
zlib.gzip(tile.data, function(err, buffer) {
if (!err) {
tile.data = buffer;
tile.isGzipped = true; tile.isGzipped = true;
} }
fn(err);
});
} }
module.exports = function(options, repo, params, id, styles) { module.exports = function(options, repo, params, id, styles) {
@ -147,12 +159,16 @@ module.exports = function(options, repo, params, id, styles) {
} }
var tile = req.tile; var tile = req.tile;
var shrinker = lookupShrinker(style); var shrinker = lookupShrinker(style);
if (shrinker) { if (!shrinker) {
unzipTile(tile); return next();
}
unzip(tile, function(err) {
if (!err) {
tile.data = shrinker(tile.data, req.params.z, tileJSON.maxzoom); tile.data = shrinker(tile.data, req.params.z, tileJSON.maxzoom);
//console.log(shrinker.getStats()); //console.log(shrinker.getStats());
} }
next(); next(err);
});
} }
function formatTile(req, res, next) { function formatTile(req, res, next) {
@ -166,7 +182,10 @@ module.exports = function(options, repo, params, id, styles) {
z = req.params.z; z = req.params.z;
tile.contentType = 'application/json'; tile.contentType = 'application/json';
unzipTile(tile); unzip(tile, function(err) {
if (err) {
return next(err);
}
var vectorTile = new VectorTile(new pbf(tile.data)); var vectorTile = new VectorTile(new pbf(tile.data));
var geojson = { var geojson = {
@ -187,6 +206,11 @@ module.exports = function(options, repo, params, id, styles) {
tile.data = JSON.stringify(geojson); tile.data = JSON.stringify(geojson);
next(); next();
});
}
function zipTile(req, res, next) {
zip(req.tile, next);
} }
function sendTile(req, res) { function sendTile(req, res) {
@ -197,9 +221,7 @@ module.exports = function(options, repo, params, id, styles) {
headers['Content-Encoding'] = 'gzip'; headers['Content-Encoding'] = 'gzip';
res.set(headers); res.set(headers);
zipTile(req.tile); res.status(200).send(req.tile.data);
return res.status(200).send(req.tile.data);
} }
app.get(tilePattern, app.get(tilePattern,
@ -207,6 +229,7 @@ module.exports = function(options, repo, params, id, styles) {
getTile, getTile,
shrinkTile, shrinkTile,
formatTile, formatTile,
zipTile,
sendTile sendTile
); );