-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
131 lines (124 loc) · 3.86 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
const axios = require('axios');
const program = require('commander');
const {prompt} = require('inquirer');
const redis = require('redis');
const client = redis.createClient();
const ip = require('ip');
const {
renderRedText,
renderBlueText,
renderGreenText,
renderYellowText,
} = require('./utilities');
// initialize dotenv
require('dotenv').config();
client.on('error', err => {
if (err.code === 'ECONNREFUSED') {
console.log(
renderRedText(
`Redis failed to connect to ${err.address} on port ${err.port}. Please start your Redis server`,
),
);
process.exit();
}
console.log(renderRedText(err));
process.exit();
});
const questions = [
{
type: 'input',
name: 'ipAddress',
message: renderBlueText(`Enter your IP address(${ip.address()}): `),
},
];
// import api key and base URL from environment variable
const {API_KEY, BASE_URL} = process.env;
program
.version('IP Finder v1.0.0')
.description('IP details CLI app, with redis cache feature');
program
.command('ipAddress')
.alias('ip')
.description('Enter the address you want to find out more about')
.action(() => {
prompt(questions).then(({ipAddress: ip}) => {
console.log('Please wait...');
client.get(ip, (err, res) => {
if (err) {
console.log(renderRedText(err));
throw err;
} else {
if (res !== null || typeof res === 'undefined') {
console.log(
renderBlueText(
`Here is the result for the address - ${ip}: ${res}`,
),
);
} else {
axios
.get(`${BASE_URL}${ip}?access_key=${API_KEY}`)
.then(response => {
console.clear();
if (response.status === 200) {
try {
const {
ip: address,
continent_name,
country_name,
city,
region_name: state,
longitude,
latitude,
type,
zip,
} = response.data;
let IPDetails = {
address,
continent: continent_name,
country: country_name,
state,
city,
longitude,
latitude,
type,
zip,
};
if (continent_name !== null) {
client.set(
address,
JSON.stringify(IPDetails),
redis.print,
10, // expiry time in seconds
);
client.get(address, (err, res) => {
if (err) {
console.log(renderRedText(err));
throw err;
}
console.log(
renderBlueText(
`Here is the result for the address - ${address}: ${res.toString()}`,
),
);
});
} else {
console.log(
renderRedText(
'I don\'t think the public IP you supplied is correct',
),
);
}
} catch (e) {
console.log(renderRedText(e));
}
} else {
console.log(renderGreenText('Connection Error'));
}
})
.catch(err => console.log(renderYellowText(err)));
}
}
});
});
});
program.parse(process.argv);