UNPKG

2.85 kBJavaScriptView Raw
1var AWS = require('aws-sdk');
2var utils = require('../lib/utils');
3var Response = require('../lib/response');
4
5module.exports = DynamoDBStreamLabel;
6
7/**
8 * Looks up the label for a stream associated with a DynamoDB table.
9 *
10 * @param {string} tableName - the name of the table
11 * @param {string} tableRegion - the region in which the table resides
12 */
13function DynamoDBStreamLabel(tableName, tableRegion) {
14 if (!tableName)
15 throw new Error('Missing Parameter TableName');
16 if (!tableRegion)
17 throw new Error('Missing Parameter TableRegion');
18
19 this.dynamodb = new AWS.DynamoDB({ region: tableRegion });
20 this.tableName = tableName;
21}
22
23/**
24 * A Lambda function to look up a stream label in response to a CloudFormation event.
25 * If the table does not have an associated stream, Create or Update events will fail.
26 *
27 * @static
28 * @param {object} event - a Lambda invocation event sent from a custom CloudFormation resource
29 * @param {object} context - the Lambda invocation context
30 * @example
31 * // a custom CloudFormation resource that is backed by this Lambda function must
32 * // provide the ARN for this Lambda function, the table's name and region.
33 * {
34 * "Type": "Custom::DynamoDBStreamLabel",
35 * "Properties": {
36 * "ServiceToken": "arn:aws:lambda:us-east-1:123456789012:function/dynamodb-stream-label",
37 * "TableName": "my-table-with-a-stream",
38 * "TableRegion": "us-east-1"
39 * }
40 * }
41 */
42DynamoDBStreamLabel.manage = function(event, context) {
43 if (!utils.validCloudFormationEvent(event))
44 return context.done(null, 'ERROR: Invalid CloudFormation event');
45
46 var response = new Response(event, context);
47
48 var requestType = event.RequestType.toLowerCase();
49 var stream;
50 try {
51 stream = new DynamoDBStreamLabel(
52 event.ResourceProperties.TableName,
53 event.ResourceProperties.TableRegion
54 );
55 } catch(err) {
56 return response.send(err);
57 }
58
59 stream[requestType](function(err, label) {
60 if (label) response.setId(label);
61 response.send(err);
62 });
63};
64
65/**
66 * Lookup the stream label
67 *
68 * @param {function} callback - a function to handle the response
69 */
70DynamoDBStreamLabel.prototype.create = function(callback) {
71 this.dynamodb.describeTable({ TableName: this.tableName }, function(err, data) {
72 if (err) return callback(err);
73
74 var label = data.Table.LatestStreamLabel;
75 if (!label) return callback(new Error('Table is not stream enabled'));
76
77 callback(null, label);
78 });
79};
80
81/**
82 * Lookup the stream label
83 *
84 * @param {function} callback - a function to handle the response
85 */
86DynamoDBStreamLabel.prototype.update = function(callback) {
87 this.create(callback);
88};
89
90/**
91 * Handle the Delete event via no-op
92 *
93 * @param {function} callback - a function to handle the response
94 */
95DynamoDBStreamLabel.prototype.delete = function(callback) {
96 callback();
97};