Created
October 11, 2016 18:06
-
-
Save henkin/91a8ece3d55b86d3899bddc629a21f1a to your computer and use it in GitHub Desktop.
AWS register IoT thing using promises
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'; | |
// https://aws.amazon.com/blogs/compute/implementing-a-serverless-aws-iot-backend-with-aws-lambda-and-amazon-dynamodb/ | |
console.log('Loading register function'); | |
var AWS = require('aws-sdk'); | |
AWS.config.region = 'us-east-1'; | |
var iot = new AWS.Iot(); | |
let policyName = 'Policy'; | |
let thingTypeName = 'Type'; | |
module.exports.register = function(event, context, callback) { | |
console.log('Received event:', JSON.stringify(event, null, 2)); | |
let thingName = event.thingName || event.body.thingName; | |
var responseData = {}; | |
var certificateArn; | |
iot.createThing({ thingName, thingTypeName }).promise() | |
.then((data) => { | |
responseData.thing = data; | |
return iot.createKeysAndCertificate({ setAsActive: true }).promise(); | |
}) | |
.then((certs) => { | |
responseData.certificates = certs; | |
certificateArn = certs.certificateArn; | |
return iot.describeEndpoint({}).promise(); | |
}) | |
.then((endpoint) => { | |
responseData.endpoint = endpoint; | |
return iot.attachPrincipalPolicy({ policyName, principal: certificateArn }).promise(); | |
}) | |
.then((data) => { | |
responseData.policyAttach = data; | |
return iot.attachThingPrincipal({ thingName, principal: certificateArn }).promise() | |
}) | |
.then((data) => { | |
responseData.thingAttach = data; | |
console.log("created thing " + thingName, responseData); | |
callback(null, responseData); | |
}) | |
.catch((err) => { | |
console.error(err); | |
callback(err) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment