Skip to content

Instantly share code, notes, and snippets.

@abrgr
Last active October 12, 2023 14:28
Show Gist options
  • Save abrgr/909c118ddd5d563f43151bc870a75a53 to your computer and use it in GitHub Desktop.
Save abrgr/909c118ddd5d563f43151bc870a75a53 to your computer and use it in GitHub Desktop.
Api Gateway with Lambda Handler
import * as path from "node:path";
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as nlambda from "aws-cdk-lib/aws-lambda-nodejs";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as apigw from "@aws-cdk/aws-apigatewayv2-alpha";
import * as apigwIntegrations from "@aws-cdk/aws-apigatewayv2-integrations-alpha";
import * as route53 from "aws-cdk-lib/aws-route53";
import * as route53Targets from "aws-cdk-lib/aws-route53-targets";
import * as cert from "aws-cdk-lib/aws-certificatemanager";
type WebhooksStackProps = cdk.StackProps & {
hostedZone: route53.IHostedZone;
};
export class WebhooksStack extends cdk.Stack {
constructor(scope: Construct, id: string, props: WebhooksStackProps) {
super(scope, id, props);
const fn = new nlambda.NodejsFunction(this, "ProcessWebhookFunction", {
description: "Webhook handler",
entry: path.join(__dirname, "..", "..", "frontend", "src", "index.ts"),
projectRoot: path.join(__dirname, "..", "..", "frontend"),
depsLockFilePath: path.join(__dirname, "..", "..", "frontend", "package-lock.json"),
handler: "handler",
memorySize: 1024,
timeout: cdk.Duration.seconds(10),
});
const prodAlias = new lambda.Alias(this, "ProcessWebhookProdAlias", {
aliasName: "prod",
version: fn.currentVersion,
});
const domainName = "in.webhooks.statebacked.dev";
const certificate = new cert.Certificate(
this,
"WebhooksApiCert",
{
domainName,
validation: cert.CertificateValidation.fromDns(props.hostedZone),
}
);
const domain = new apigw.DomainName(
this,
"WebhooksApiDomainName",
{
domainName,
certificate,
}
);
const api = new apigw.HttpApi(this, "WebhookApi", {
defaultDomainMapping: {
domainName: domain,
}
});
new route53.ARecord(this, "WebhooksRecord", {
zone: props.hostedZone,
recordName: "in",
target: route53.RecordTarget.fromAlias(
new route53Targets.ApiGatewayv2DomainProperties(
domain.regionalDomainName,
domain.regionalHostedZoneId
)
),
});
new apigw.HttpRoute(this, "ProcessWebhookRoute", {
httpApi: api,
routeKey: apigw.HttpRouteKey.with("/{orgId}/{provider}", apigw.HttpMethod.POST),
integration: new apigwIntegrations.HttpLambdaIntegration(
"ProcessWebhookIntegration",
prodAlias,
),
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment