Get topojson-files and caches them in an Redis-database. Used for faster response.
const http = require('http');
const request = require('request');
const redis = require("redis");
const zlib = require('zlib');
const config = require('./config.js');
const rclient = redis.createClient(config.redis.port, config.redis.host, {'return_buffers': true});
function sendData(res, data, scode) {
res.writeHead(scode, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
'Content-Encoding': 'gzip',
'Content-Type': 'application/json'
});
res.end(data);
}
var server = http.createServer(function (sReq, sRes) {
if(!sReq.url.match(/^\/\d+\/\d+\/\d+\.topojson$/)) {
// Non Regex
sRes.writeHead(404);
sRes.end();
return;
}
rclient.get(sReq.url.slice(1, -9), function(err, miData) {
if(miData) {
// From Redis
sendData(sRes, miData, 200);
} else {
var reqOptions = {
method: 'GET',
uri: config.mapzen.protocol+"://"+config.mapzen.rurl+config.mapzen.layer+sReq.url+"?api_key="+config.mapzen.key,
gzip: true
};
request(reqOptions, function(mErr, mRes, mData) {
// From Mapzen
zlib.gzip(mData, function (err, zmRes) {
sendData(sRes, zmRes, mRes.statusCode);
if(mRes.statusCode == 200 && zmRes) {
rclient.set(sReq.url.slice(1, -9), zmRes);
rclient.expire(sReq.url.slice(1, -9), config.redis.timeCached);
}
});
});
}
});
});
server.listen(config.server.port);
module.exports = {
"server": {
"port": 10025
},
"redis": {
"host": "localhost",
"port": 6379,
"timeCached": 60 * 60 * 24 * 14
},
"mapzen": {
"layer": "all",
"protocol": "http",
"rurl": 'tile.mapzen.com/mapzen/vector/v1/',
"key": 'VALID_MAPZEN_KEY'
}
};