Skip to content

Instantly share code, notes, and snippets.

@geopet
Last active April 12, 2018 18:46
Show Gist options
  • Save geopet/c9ed74b915b843d6bfeb0490a7a6e95f to your computer and use it in GitHub Desktop.
Save geopet/c9ed74b915b843d6bfeb0490a7a6e95f to your computer and use it in GitHub Desktop.
simple node weather app
const axios = require('axios');
const yargs = require('yargs');
const argv = yargs
.options({
a: {
demand: true,
alias: 'address',
describe: 'Address to fetch weather for.',
string: true
}
})
.help()
.alias('help', 'h')
.argv;
const encodedAddress = encodeURIComponent(argv.a);
async function geocoder(encodedAddress) {
const googleKey = 'add-key';
try {
const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${googleKey}`;
const geocodeData = await axios.get(geocodeUrl);
return geocodeData;
} catch(e) {
console.log('Throwing error from geocoder.');
throw new Error(e);
}
}
async function weatherForecast(lat, lng) {
const darkskyKey = 'add key'
try {
const weatherUrl = `https://api.darksky.net/forecast/${darkskyKey}/${lat},${lng}`
const weatherData = await axios.get(weatherUrl);
return weatherData;
} catch(e) {
console.log('Error in weather function');
throw new Error(e);
}
}
async function execute(encodedAddress) {
try {
const geocodeData = await geocoder(encodedAddress);
const { lat, lng } = geocodeData.data.results[0].geometry.location;
const weatherData = await weatherForecast(lat, lng);
console.log(JSON.stringify(weatherData.data, undefined, 2));
} catch(e) {
console.log('Error in call.');
console.log(e);
}
}
execute(encodedAddress);
const axios = require('axios');
const yargs = require('yargs');
const googleKey = 'add key';
const darkskyKey = 'add key'
const argv = yargs
.options({
a: {
demand: true,
alias: 'address',
describe: 'Address to fetch weather for.',
string: true
}
})
.help()
.alias('help', 'h')
.argv;
const encodedAddress = encodeURIComponent(argv.a);
const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${googleKey}`
axios.get(geocodeUrl).then((response) => {
const lat = response.data.results[0].geometry.location.lat;
const lng = response.data.results[0].geometry.location.lng;
const weatherUrl = `https://api.darksky.net/forecast/${darkskyKey}/${lat},${lng}`
return axios.get(weatherUrl);
}).then((response) => {
console.log(JSON.stringify(response.data, undefined, 2));
}).catch((e) => {
console.log(e);
});
{
"name": "weather-app",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.18.0",
"yargs": "^11.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment