Last active
August 23, 2016 22:14
-
-
Save jshin49/8eb3a08d6cc5cc498edda321c6c68ae2 to your computer and use it in GitHub Desktop.
Open weather implementation of AWS lambda
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
'use strict'; | |
let http = require('http'); | |
/** | |
* Pass the data to send as `event.data`, and the request options as | |
* `event.options`. For more information see the HTTPS module documentation | |
* at https://nodejs.org/api/https.html. | |
* | |
* Will succeed with the response body. | |
*/ | |
exports.handler = (event, context) => { | |
if (!event.city) { | |
context.succeed("Please enter a city"); | |
} | |
console.log(event.city); | |
var api_base_url = "http://api.openweathermap.org/data/2.5/weather?q="; | |
api_base_url += event.city; | |
api_base_url += "&APPID=38a5ea89e1ee220a5c7dbdbd04c9a67d"; | |
console.log(api_base_url); | |
const req = http.request(api_base_url, (res) => { | |
let body = ''; | |
console.log('Status:', res.statusCode); | |
console.log('Headers:', JSON.stringify(res.headers)); | |
res.setEncoding('utf8'); | |
res.on('data', (chunk) => body += chunk); | |
res.on('end', () => { | |
console.log('Successfully processed HTTP response'); | |
// If we know it's JSON, parse it | |
if (res.headers['content-type'].indexOf('application/json') !== -1) { | |
console.log("JSON"); | |
body = JSON.parse(body); | |
console.log(body); | |
if (body.cod == 401) { | |
console.log(res.statusCode); | |
context.succeed(body.cod + " " + body.message); | |
} | |
else { | |
context.succeed(body.weather[0].main); | |
} | |
} | |
}); | |
}); | |
req.on('error', () => { | |
console.log("Error"); | |
}); | |
req.end(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment