Define the HitCounter API

Create a new file for our hit counter construct #

Create a new file under lib called hitcounter.ts with the following content:

import * as cdk from "aws-cdk-lib";
import * as lambda from "aws-cdk-lib/aws-lambda";
import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs";
import { Construct } from "constructs";

export interface HitCounterProps {
  /** the function for which we want to count url hits **/
  downstream: lambda.IFunction;
}

export class HitCounter extends Construct {
  constructor(scope: Construct, id: string, props: HitCounterProps) {
    super(scope, id);

    // TODO
  }
}

Save the file. Oops, an error! No worries, we’ll be using props shortly.

What’s going on here? #

  • We declared a new construct class called HitCounter.
  • As usual, constructor arguments are scope, id and props. And as usual, we propagate scope and id to the cdk.Construct base class.
  • The props argument is of type HitCounterProps which includes a single property downstream of type lambda.IFunction. This is where we are going to “plug in” the Lambda function we created in the previous chapter so it can be hit-counted.

Next, we are going to write the handler code of our hit counter.

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

More information