Add caching of IP info

This commit is contained in:
Alex Janka 2017-06-02 21:47:17 +10:00
parent bc17ff8b7b
commit 0dfc40d2b0

View file

@ -3,10 +3,12 @@ import expresshb = require('express-handlebars');
import http = require('http'); import http = require('http');
import https = require('https'); import https = require('https');
import Promise = require('promise'); import Promise = require('promise');
import HashMap = require('hashmap');
import { IPGeoJson } from './ip_geo'; import { IPGeoJson } from './ip_geo';
var app = express(); var app = express();
var cache = new HashMap();
app.engine('handlebars', expresshb({ defaultLayout: 'main' })); app.engine('handlebars', expresshb({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars'); app.set('view engine', 'handlebars');
@ -48,11 +50,17 @@ function getIpInfo(ip: String): Promise.IThenable<{}> {
}); });
response.on('end', function () { response.on('end', function () {
console.log(str); var result = <IPGeoJson>JSON.parse(str.slice(9));
resolve(<IPGeoJson>JSON.parse(str.slice(9))); cache.set(ip, result);
resolve(result);
}); });
} }
var cached = cache.get(ip);
if (cached != null) {
resolve(cached);
} else {
https.get(options, callback); https.get(options, callback);
}
}) })
} }