Created
January 31, 2019 20:04
-
-
Save welbesw/0e39d51bf8d5244c8d52af7ec56bcd5b to your computer and use it in GitHub Desktop.
Coffee Brewed Lambda Function
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
const AWS = require('aws-sdk'); | |
const https = require('https'); | |
const DynamoDB = new AWS.DynamoDB(); | |
const SLACK_PROTOCOL = 'https:'; | |
const SLACK_HOST = 'hooks.slack.com'; | |
const SLACK_PATH = '/services/YOUR-SLACK-PATH-HERE'; | |
async function postToSlack(event) { | |
var coffeeType = event.clickType == 'SINGLE' ? 'Regular' : 'Decaf' | |
var color = event.clickType == 'SINGLE' ? '#158f64' : '#c7600c' | |
var message = coffeeType + " :coffee: brewed! "; | |
return new Promise((resolve, reject) => { | |
const post_data = JSON.stringify({ | |
"attachments": [ | |
{ | |
"fallback": message, | |
"title": message, | |
"image_url": "https://s3.amazonaws.com/centare/coffee-brewed.gif", | |
"color": color | |
} | |
] | |
}); | |
const options = { | |
protocol: SLACK_PROTOCOL, | |
host: SLACK_HOST, | |
path: SLACK_PATH, | |
method: 'POST', | |
headers: { | |
'Content-Type': 'Content-type: application/json', | |
'Content-Length': Buffer.byteLength(post_data), | |
} | |
}; | |
const req = https.request(options, (res) => { | |
res.setEncoding('utf8'); | |
console.log("Response status code: " + res.statusCode); | |
res.on('data', function (body) { | |
console.log(body); | |
}); | |
resolve('Success'); | |
}); | |
req.on('error', (e) => { | |
reject(e.message); | |
}); | |
// send the request | |
req.write(post_data); | |
req.end(); | |
}); | |
} | |
async function recordEvent(event) { | |
return new Promise((resolve, reject) => { | |
var item = { | |
'id': { 'N': new Date().getTime().toString() }, | |
'serialNumber': {'S':event.serialNumber}, | |
'batteryVoltage': {'S':event.batteryVoltage}, | |
'clickType': {'S':event.clickType}, | |
}; | |
DynamoDB.putItem({ | |
'TableName': 'coffee_button_press', | |
'Item': item | |
}, function(err, data) { | |
if (err) { | |
console.log("Error in putItem " + err); | |
reject(err.message); | |
} else { | |
console.log("Successfully Inserted"); | |
resolve('Success'); | |
} | |
}); | |
}); | |
} | |
exports.handler = async (event) => { | |
await postToSlack(event); | |
return await recordEvent(event); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment