Use the hit counter

Add a hit counter to our stack #

Okay, our hit counter is ready. Let’s use it in our app. Open main.ts and add the following highlighted code:

import { App } from "cdktf";
import { Construct } from "constructs";
import { AwsStack, AwsStackProps } from "terraconstructs/aws";
import {
  Code,
  LambdaFunction,
  Runtime,
  LambdaRestApi,
} from "terraconstructs/aws/compute";
import { HitCounter } from "./lib/hitcounter";

class MyStack extends AwsStack {
  constructor(scope: Construct, id: string, props: AwsStackProps) {
    super(scope, id, props);

    // defines an AWS Lambda resource
    const hello = new LambdaFunction(this, "HelloHandler", {
      runtime: Runtime.NODEJS_22_X,
      code: Code.fromAsset("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 LambdaRestApi(this, "Endpoint", {
      cloudWatchRole: false,
      handler: helloWithCounter.handler,
      registerOutputs: true,
    });
  }
}

const app = new App();
new MyStack(app, "cdk-workshop", {
  environmentName: "dev",
  gridUUID: "cdk-workshop-dev",
  providerConfig: {
    region: "us-east-1",
  },
});
app.synth();

Notice that we changed our API Gateway handler to helloWithCounter.handler instead of hello. This basically means that whenever our endpoint is hit, API Gateway will route the request to our hit counter handler, which will log the hit and relay it over to the hello function. Then, the responses will be relayed back in the reverse order all the way to the user.

Deploy #

cdktf deploy

It might take a little while.

And the output:

cdk-workshop
  EndpointOutputs = {
    "restApiId": "xxxxxxxxxx",
    "restApiName": "cdkworkshopEndpoint424A4D39",
    "restApiRootResourceId": "yyyyyyyy",
    "url": "https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/"
  }

Test #

Okay, ready to give this a go? (you should, again, see the URL of your API in the output of the “deploy” command).

Use curl or your web browser to hit your endpoint (we use -i to show HTTP response fields and status code):

curl -i https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/

Oh no… seems like something went wrong:

HTTP/2 502 Bad Gateway
...

{"message": "Internal server error"}

Let’s see how to find out what happened and fix it.




We use analytics to make this content better, but only with your permission.

More information