Created
March 24, 2017 18:59
-
-
Save jasonsperske/7c0e59ffbf342c1a001ac70f55d65e1d to your computer and use it in GitHub Desktop.
Fetches a RandomVictory and sends it to a IFTTT Maker WebHook (defiend in envrionment varibles)
This file contains 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'; | |
var https = require('https'); | |
function fetchVictory(then, context, callback) { | |
var options = { | |
hostname: "randomvictory.com", | |
port: 443, | |
path: "/random.json", | |
method: "GET" | |
} | |
var request = https.request(options, function (response) { | |
var result = ''; | |
response.on('data', function (chunk) { | |
result += chunk; | |
}); | |
response.on('end', function () { | |
var random = JSON.parse(result); | |
console.log(result); | |
then(random.victory.name, random.victory.href, context, callback); | |
}); | |
response.on('error', function (err) { | |
console.log(err); | |
callback(new Error("RandomVictory failed to load")); | |
}) | |
}); | |
// req error | |
request.on('error', function (err) { | |
console.log(err); | |
callback(new Error("RandomVictory failed to load")); | |
}); | |
request.end(); | |
} | |
function sendVictory(name, url, context, callback) { | |
var body = JSON.stringify({ | |
value1: name, | |
value2: url | |
}), | |
options = { | |
hostname: "maker.ifttt.com", | |
port: 443, | |
path: `/trigger/${process.env.IFTTT_MAKER_EVENT}/with/key/${process.env.IFTTT_MAKER_KEY}`, | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
"Content-Length": Buffer.byteLength(body) | |
} | |
}; | |
var request = https.request(options, function (response) { | |
var result = ''; | |
response.on('data', function (chunk) { | |
result += chunk; | |
}); | |
response.on('end', function () { | |
console.log(result); | |
context.done(); | |
}); | |
response.on('error', function (err) { | |
console.log(err); | |
callback(new Error("IFTTT failed to send")); | |
}) | |
}); | |
// req error | |
request.on('error', function (err) { | |
console.log(err); | |
callback(new Error("IFTTT failed to send")); | |
}); | |
//send request witht the postData form | |
request.write(body); | |
request.end(); | |
} | |
exports.handler = (event, context, callback) => { | |
if (event.clickType != "SINGLE") { | |
return; | |
} | |
fetchVictory(sendVictory, context, callback); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment