Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Created July 28, 2015 15:33
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 DinoChiesa/99351cc50abe13a0cee0 to your computer and use it in GitHub Desktop.
Save DinoChiesa/99351cc50abe13a0cee0 to your computer and use it in GitHub Desktop.
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