udemy-node-weather-app/app-promise.js
Tyrel Souza 5de82e2431 promise
2017-12-01 00:33:19 -05:00

47 lines
1.4 KiB
JavaScript

const yargs = require('yargs');
const axios = require('axios');
const credentials = require("./credentials")
const argv = yargs
.options({
a: {
demand: true,
alias: 'address',
describe: "Address to fetch weather for.",
string: true
}
})
.help()
.alias('help', 'h')
.argv;
var encodedAddress = encodeURIComponent(argv.address);
var geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${credentials.GOOGLE_API_KEY}`;
axios.get(geocodeUrl).then((response) => {
if (response.data.status === "ZERO_RESULTS") {
throw new Error('Unable to find that Address.')
} else if (response.data.status === 'REQUEST_DENIED'){
throw new Error(`API Request Denied: ${response.data.error_message}`);
}
var loc = response.data.results[0].geometry.location;
console.log(response.data.results[0].formatted_address);
var weatherUrl = `https://api.darksky.net/forecast/${API_KEY}/${loc.lat},${loc.lng}`;
return axios.get(weatherUrl);
}).then((response) => {
var temperature = response.data.currently.temperature;
var apparentTemperature = response.data.currently.apparentTemperature;
console.log(`It's currently: ${temperature}. It feels like ${apparentTemperature}`);
})
.catch((e) => {
if (e.code === 'ENOTFOUND') {
console.log("Unable to connect to API servers");
} else {
console.log(e.message);
}
})
console.log("Powered By https://darksky.net/poweredby/");