Skip to content

Instantly share code, notes, and snippets.

@jshin49

jshin49/aws-openweather.js

Last active Aug 23, 2016
Embed
What would you like to do?
Open weather implementation of AWS lambda
'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