Edit hitcounter.ts
and modify it as such table
is exposed as a public property.
import cdk = require('@aws-cdk/cdk');
import lambda = require('@aws-cdk/aws-lambda');
import dynamodb = require('@aws-cdk/aws-dynamodb');
export interface HitCounterProps {
/** the function for which we want to count url hits **/
downstream: lambda.Function;
}
export class HitCounter extends cdk.Construct {
/** allows accessing the counter function */
public readonly handler: lambda.Function;
/** the hit counter table */
public readonly table: dynamodb.Table;
constructor(scope: cdk.Construct, id: string, props: HitCounterProps) {
super(scope, id);
const table = new dynamodb.Table(this, 'Hits');
table.addPartitionKey({ name: 'path', type: dynamodb.AttributeType.String });
this.table = table;
this.handler = new lambda.Function(this, 'HitCounterHandler', {
runtime: lambda.Runtime.NodeJS810,
handler: 'hitcounter.handler',
code: lambda.Code.asset('lambda'),
environment: {
DOWNSTREAM_FUNCTION_NAME: props.downstream.functionName,
HITS_TABLE_NAME: table.tableName
}
});
// grant the lambda role read/write permissions to our table
table.grantReadWriteData(this.handler.role);
// grant the lambda role invoke permissions to the downstream function
props.downstream.grantInvoke(this.handler.role);
}
}
Go back to cdk-workshop-stack.ts
and assign the table
property of the table viewer:
import cdk = require('@aws-cdk/cdk');
import lambda = require('@aws-cdk/aws-lambda');
import apigw = require('@aws-cdk/aws-apigateway');
import { HitCounter } from './hitcounter';
import { TableViewer } from 'cdk-dynamo-table-viewer';
export class CdkWorkshopStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, name, props);
const hello = new lambda.Function(this, 'HelloHandler', {
runtime: lambda.Runtime.NodeJS810,
code: lambda.Code.asset('lambda'),
handler: 'hello.handler'
});
const helloWithCounter = new HitCounter(this, 'HelloHitCounter', {
downstream: hello
});
// defines an API Gateway REST API resource backed by our "hello" function.
new apigw.LambdaRestApi(this, 'Endpoint', {
handler: helloWithCounter.handler
});
new TableViewer(this, 'ViewHitCounter', {
title: 'Hello Hits',
table: helloWithCounter.table
});
}
}
We’re finished making code changes,
so once you save this file,
you can close the npm run watch
command with Ctrl-C
.