Created
July 28, 2015 15:33
-
-
Save DinoChiesa/99351cc50abe13a0cee0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'), // 4.x | |
bodyParser = require('body-parser'), // express 4.x requires this | |
yql = require('yql'), | |
urlparse = require('url'); | |
// Set up Express environment and enable it to read and write JSON bodies | |
var app = express(); | |
app.use(bodyParser.json()); // for parsing application/json | |
// Generic Send Error Function | |
function sendError(res, code, msg) { | |
var o = { 'error': msg }; | |
res.writeHead(code, {'Content-Type': 'application/json'}); | |
res.end(JSON.stringify(o)); | |
} | |
// The API starts here | |
// GET / | |
app.get('/', function(req, res) { | |
var rootTemplate = { | |
'weather' : { 'href' : '/forecast' } | |
}; | |
res.header('Content-Type', 'application/json') | |
.status(200) | |
.send(JSON.stringify(rootTemplate)); | |
}); | |
// GET /forecast | |
app.get('/forecast', function(req, res) { | |
try { | |
// parse the url and check for zipcode | |
var parsed = urlparse.parse(req.url, true); | |
if (!parsed.query.zipcode) { | |
sendError(res, 400, 'Missing query parameter "zipcode"'); | |
} | |
else { | |
// create the query per YQL module documentation & then execute the query | |
var forecastQuery = 'SELECT * FROM weather.forecast WHERE (location = ' + | |
parsed.query.zipcode + ')'; | |
var query = new yql(forecastQuery); | |
// execute the query and create/send the final response in the | |
// anonymous callback function | |
query.exec(function(err, data) { | |
var finalResponse = { | |
location : data.query.results.channel.location, | |
units : data.query.results.channel.units, | |
condition : data.query.results.channel.item.condition, | |
forecast : data.query.results.channel.item.forecast | |
}; | |
res.header('Content-Type', 'application/json') | |
.status(200) | |
.send(JSON.stringify(finalResponse)); | |
}); | |
} | |
} | |
catch(e) { | |
sendError(res, 500, "Internal Server Error - " + e.message); | |
} | |
}); | |
// all other requests | |
app.all(/^\/.*/, function(request, response) { | |
response.header('Content-Type', 'application/json') | |
.status(404) | |
.send('{ "message" : "This is not the server you\'re looking for." }\n'); | |
}); | |
// start the server | |
app.listen(process.env.PORT || 9000, function() { | |
console.log('The server is running!'); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment