Skip to content

Instantly share code, notes, and snippets.

@mantonx
Created September 28, 2017 21:52
Show Gist options
  • Save mantonx/682555af1a03ee25905a9419323db386 to your computer and use it in GitHub Desktop.
Save mantonx/682555af1a03ee25905a9419323db386 to your computer and use it in GitHub Desktop.
Weather Forecast Service on Lambda Edge
const https = require("https");
const darksky_endpoint = 'https://api.darksky.net/forecast/37737016f7549777487b431061f4e220/';
const geocode_enpoint = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=';
exports.handler = function(event, context, callback) {
if (event.Records) {
const request = event.Records[0].cf.request;
getForecast(callback, request);
}
}
const getForecast = function ( callback, request ) {
let params = request.uri.split('/');
params = params[params.length - 1];
if (params) {
params = encodeURI(params);
Request(callback, ProcessGeoLocation, params, request, geocode_enpoint);
}
}
const ProcessGeoLocation = function ( callback, request_event, response ) {
const results = response.results[0];
request_event.coords = {
loc: results.address_components,
lat: results.geometry.location.lat,
lng: results.geometry.location.lng
};
const params = request_event.coords.lat + ',' + request_event.coords.lng;
Request(callback, ProcessWeatherForecast, params, request_event, darksky_endpoint);
}
const ProcessWeatherForecast = function(callback, request_event, response) {
const response_event = {
status: '200',
statusDescription: 'HTTP OK',
httpVersion: request_event.httpVersion,
body: JSON.stringify({
weather: response.currently,
location: request_event.coords,
}),
headers: {
'cache-control': [{
key: 'Cache-Control',
value: 'max-age=5'
}],
'content-type': [{
key: 'Content-Type',
value: 'application/json'
}],
},
};
callback(null, response_event);
}
let Request = function( callback, local_callback, params, request_event, endpoint ) {
let request = https.get(endpoint + params, res => {
let response = '';
res.setEncoding("utf8");
res.on("data", data => {
response += data;
});
res.on("end", () => {
response = JSON.parse(response);
if (local_callback) {
local_callback(callback, request_event, response);
}
});
}).on('error', (e) => {
console.error(e);
});
}
const parseQueryString = function( queryString ) {
let params = {}, queries, temp, i, l;
// Split into key/value pairs
queries = queryString.split("&");
// Convert the array of strings into an object
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment