Getting info works as a promise!!!!!!

This commit is contained in:
Alex Janka 2017-06-02 21:16:55 +10:00
parent 2c1956312a
commit 8e4ecd3773
2 changed files with 29 additions and 37 deletions

View file

@ -2,7 +2,7 @@ import express = require('express');
import expresshb = require('express-handlebars'); 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 { IPGeoJson } from './ip_geo'; import { IPGeoJson } from './ip_geo';
@ -12,48 +12,38 @@ app.engine('handlebars', expresshb({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars'); app.set('view engine', 'handlebars');
app.get('/', function (req, res) { app.get('/', function (req, res) {
res.render('home'); getIpInfo("::ffff:" + "119.17.156.106").done(function (geoinfo: IPGeoJson) {
getIpInfo("::ffff:" + "119.17.156.106").country; //replace with req.ip res.render('home');
}); //replace with req.ip
}); });
app.listen(3000); app.listen(3000);
function getIpInfo(ip: String): IPGeoJson { function getIpInfo(ip: String): Promise.IThenable<{}> {
var ipinfo: IPGeoJson = { return new Promise(function (resolve, reject) {
ip: "", var options = {
city: "", host: 'ipinfo.io',
region: "", port: 443,
country: "", path: '/' + ip + '/geo',
loc: "", method: 'GET',
postal: "" headers: {
}; 'Content-Type': 'application/json'
}
var options = {
host: 'ipinfo.io',
port: 443,
path: '/' + ip + '/geo',
method: 'GET',
headers: {
'Content-Type': 'application/json'
} }
}
console.log(options.path);
var callback = function (response: http.IncomingMessage) { var callback = function (response: http.IncomingMessage) {
var str: string; var str: string;
response.on('data', function (chunk) { response.on('data', function (chunk) {
str += chunk; str += chunk;
}); });
response.on('end', function () { response.on('end', function () {
console.log(str); console.log(str);
ipinfo = <IPGeoJson>JSON.parse(str.slice(9)); resolve(<IPGeoJson>JSON.parse(str.slice(9)));
console.log(ipinfo.city); });
}); }
}
https.get(options, callback); https.get(options, callback);
})
return ipinfo;
} }

View file

@ -17,10 +17,12 @@
"@types/express-handlebars": "0.0.29", "@types/express-handlebars": "0.0.29",
"@types/handlebars": "^4.0.32", "@types/handlebars": "^4.0.32",
"@types/node": "^7.0.23", "@types/node": "^7.0.23",
"@types/promise": "^7.1.30",
"express": "^4.15.3", "express": "^4.15.3",
"express-handlebars": "^3.0.0", "express-handlebars": "^3.0.0",
"handlebars": "^4.0.10", "handlebars": "^4.0.10",
"nodemon": "^1.11.0", "nodemon": "^1.11.0",
"promise": "^7.1.1",
"ts-node": "^3.0.4", "ts-node": "^3.0.4",
"typescript": "^2.3.4" "typescript": "^2.3.4"
}, },