Skip to content

Rebuild using CDK #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
.node_modules
npm_debug.log
.vscode
.DS_Store
.idea
output.yml
node_modules
.cdk
.cdk.staging/
56 changes: 56 additions & 0 deletions ApiLambdaDynamoDBStack.template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
Transform: AWS::Serverless-2016-10-31
Resources:
viewerstable25A8B0A8:
Type: AWS::DynamoDB::Table
Properties:
KeySchema:
- AttributeName: viewerId
KeyType: HASH
AttributeDefinitions:
- AttributeName: viewerId
AttributeType: S
BillingMode: PAY_PER_REQUEST
TableName: twitchViewers
Metadata:
aws:cdk:path: ApiLambdaDynamoDBStack/viewers-table/Resource
viewersApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
Cors: '"*"'
Metadata:
aws:cdk:path: ApiLambdaDynamoDBStack/viewersApi
SaveToDynamoDB:
Type: AWS::Serverless::Function
Properties:
CodeUri: src
Handler: index.handler
Runtime: nodejs8.10
Environment:
Variables:
TABLE_NAME:
Ref: viewerstable25A8B0A8
PRIMARY_KEY: viewerId
Events:
save:
Properties:
Method: POST
Path: /viewers
RestApiId: viewersApi
Type: Api
saveOptions:
Properties:
Method: OPTIONS
Path: /viewers
RestApiId: viewersApi
Type: Api
Policies: |-2

- DynamoDBCrudPolicy:
TableName: twitchViewers
Metadata:
aws:cdk:path: ApiLambdaDynamoDBStack/SaveToDynamoDB
CDKMetadata:
Type: AWS::CDK::Metadata
Properties:
Modules: aws-cdk=0.32.0,@aws-cdk/assets=0.32.0,@aws-cdk/aws-applicationautoscaling=0.32.0,@aws-cdk/aws-autoscaling-common=0.32.0,@aws-cdk/aws-cloudwatch=0.32.0,@aws-cdk/aws-dynamodb=0.32.0,@aws-cdk/aws-ec2=0.32.0,@aws-cdk/aws-events=0.32.0,@aws-cdk/aws-iam=0.32.0,@aws-cdk/aws-kms=0.32.0,@aws-cdk/aws-lambda=0.32.0,@aws-cdk/aws-s3=0.32.0,@aws-cdk/aws-s3-notifications=0.32.0,@aws-cdk/aws-sam=0.32.0,@aws-cdk/aws-sqs=0.32.0,@aws-cdk/cdk=0.32.0,@aws-cdk/cx-api=0.32.0,@aws-cdk/region-info=0.32.0,jsii-runtime=node.js/v10.15.3
8 changes: 8 additions & 0 deletions bin/api-lambda-save-dynamodb.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions bin/api-lambda-save-dynamodb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import 'source-map-support/register';
import cdk = require('@aws-cdk/cdk');
import { ApiLambdaSaveDynamoDBStack } from '../lib/api-lambda-save-dynamodb-stack';

const app = new cdk.App();
new ApiLambdaSaveDynamoDBStack(app, 'ApiLambdaDynamoDBStack');
3 changes: 3 additions & 0 deletions cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "node bin/api-lambda-save-dynamodb"
}
38 changes: 19 additions & 19 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,27 @@ const IS_CORS = process.env.IS_CORS;
const PRIMARY_KEY = process.env.PRIMARY_KEY;

exports.handler = (event) => {
if (event.httpMethod === 'OPTIONS') {
return Promise.resolve(processResponse(IS_CORS));
}
if (!event.body) {
return Promise.resolve(processResponse(IS_CORS, 'invalid', 400));
}
let item = JSON.parse(event.body);
item[PRIMARY_KEY] = uuidv4();
let params = {
TableName: TABLE_NAME,
Item: item
}
return dynamoDb.put(params)
if (event.httpMethod === 'OPTIONS') {
return Promise.resolve(processResponse(IS_CORS));
}
if (!event.body) {
return Promise.resolve(processResponse(IS_CORS, 'invalid', 400));
}
let item = JSON.parse(event.body);
item[PRIMARY_KEY] = uuidv4();
let params = {
TableName: TABLE_NAME,
Item: item
}
return dynamoDb.put(params)
.promise()
.then(() => (processResponse(IS_CORS)))
.catch(dbError => {
let errorResponse = `Error: Execution update, caused a Dynamodb error, please look at your logs.`;
if (dbError.code === 'ValidationException') {
if (dbError.message.includes('reserved keyword')) errorResponse = `Error: You're using AWS reserved keywords as attributes`;
}
console.log(dbError);
return processResponse(IS_CORS, errorResponse, 500);
let errorResponse = `Error: Execution update, caused a Dynamodb error, please look at your logs.`;
if (dbError.code === 'ValidationException') {
if (dbError.message.includes('reserved keyword')) errorResponse = `Error: You're using AWS reserved keywords as attributes`;
}
console.log(dbError);
return processResponse(IS_CORS, errorResponse, 500);
});
};
87 changes: 87 additions & 0 deletions lib/api-lambda-save-dynamodb-stack.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

90 changes: 90 additions & 0 deletions lib/api-lambda-save-dynamodb-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import cdk = require('@aws-cdk/cdk');
import { CfnFunction, CfnApi } from '@aws-cdk/aws-sam';
import { AssetCode } from '@aws-cdk/aws-lambda';
import { Table, AttributeType, BillingMode } from '@aws-cdk/aws-dynamodb';
//import { RestApi, LambdaIntegration, IResource, MockIntegration, PassthroughBehavior } from '@aws-cdk/aws-apigateway';

export class ApiLambdaSaveDynamoDBStack extends cdk.Stack {

constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

const tableName = 'twitchViewers';

const primaryKeyName = 'viewerId';
const table = new Table(this, 'viewers-table', {
tableName: tableName,
partitionKey: {
name: primaryKeyName,
type: AttributeType.String
},
billingMode: BillingMode.PayPerRequest
});

const api = new CfnApi(this, 'viewersApi', {
stageName: 'prod',
cors: '"*"'
});

new CfnFunction(this, 'SaveToDynamoDB', {
codeUri: new AssetCode('src').path,
handler: 'index.handler',
runtime: 'nodejs8.10',
environment: {
variables: {
TABLE_NAME: table.tableName,
PRIMARY_KEY: primaryKeyName
}
},
policies: `
- DynamoDBCrudPolicy:
TableName: ${tableName}`,
events: {
save: {
type: 'Api',
properties: {
path: '/viewers',
method: 'POST',
restApiId: api.logicalId
}
},
saveOptions: {
type: 'Api',
properties: {
path: '/viewers',
method: 'OPTIONS',
restApiId: api.logicalId
}
}
}
});
}
}

/*function addCorsOptions(apiResource: IResource) {
apiResource.addMethod('OPTIONS', new MockIntegration({
integrationResponses: [{
statusCode: '200',
responseParameters: {
'method.response.header.Access-Control-Allow-Headers': "'ContentType,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'",
'method.response.header.Access-Control-Allow-Origin': "'*'",
'method.response.header.Access-Control-Allow-Credentials': "'false'",
'method.response.header.Access-Control-Allow-Methods': "'OPTIONS,POST,PUT'",
}
}],
passthroughBehavior: PassthroughBehavior.Never,
requestTemplates: {
"application/json": "{\"statusCode\":200}"
}
}), {
methodResponses: [{
statusCode: '200',
responseParameters: {
'method.response.header.Access-Control-Allow-Headers': true,
'method.response.header.Access-Control-Allow-Origin': true,
'method.response.header.Access-Control-Allow-Credentials': true,
'method.response.header.Access-Control-Allow-Methods': true,
}
}]
});
}*/
Loading