Skip to content

Instantly share code, notes, and snippets.

@RabeaWahab
Last active May 7, 2018 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RabeaWahab/f29f97ebbe15402b889474bcc27fbc88 to your computer and use it in GitHub Desktop.
Save RabeaWahab/f29f97ebbe15402b889474bcc27fbc88 to your computer and use it in GitHub Desktop.
/*
* The weathermap application.
*/
var express = require('express');
var request = require('request');
// Rabea: checkout out Dotenv module, it is a better way of handling creds
var config = require('./config');
var app = express();
// API endpoint to check US weather information by zip code
app.get('/zipcode/:zipc', function(req, res) {
var zipcode = req.params.zipc;
if(validateConfig()){
if (validZipcode(zipcode)){
request.get({url:'http://api.openweathermap.org/data/2.5/weather?zip=' + zipcode+ '&appid=' + config.apiKey},
function(error, response, body){
if (!error && response.statusCode === 200) {
res.status(200);
// Rabea: you will need a parse the body to send it back as JSON format, since now it is being sent as a string
res.json(JSON.parse(body));
} else {
res.status(500);
res.json(error);
}
});
} else {
res.status(200);
res.json({'error':zipcode + ' Is not a valid US zip code!'});
}
} else {
// Rabea: you can send Unauthorized 401 instead since it is missing credentials
res.status(200);
res.json({'error':'You need to configure the apiKey!'});
}
});
// Start the server in the port 3000 !
app.listen(config.server_port, function () {
console.log('Listening on port :' + config.server_port);
});
// Change the 404 message modifing the middleware
app.use(function(req, res, next) {
res.status(404).send("Sorry, that route doesn't exist.");
});
// Check if is a valid US zip code
function validZipcode(zipcode){
var RegExp = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
return RegExp.test(zipcode);
}
// Check if apiKey was configured
function validateConfig(){
if(config.apiKey === ''){
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment