Add a hit counter to our stack #
Okay, our hit counter is ready. Let’s use it in our app. Open lib/cdk-workshop-stack.ts
and add
the following highlighted code:
import * as cdk from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as apigw from "aws-cdk-lib/aws-apigateway";
import { HitCounter } from "./hitcounter";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import * as path from "path";
export class CdkWorkshopStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const hello = new NodejsFunction(this, "HelloHandler", {
runtime: lambda.Runtime.NODEJS_20_X,
entry: path.join(__dirname, "../lambda/hello.ts"),
handler: "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,
});
}
}
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 #
cdk deploy
It might take a little while.
And the output:
CdkWorkshopStack.Endpoint8024A810 = 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.