-
-
Save SethThomas/fa769197be405e3ec5c147933e5dd021 to your computer and use it in GitHub Desktop.
API Gateway v2 SQS Proxy Integration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as sst from "@serverless-stack/resources"; | |
import * as sqs from "@aws-cdk/aws-sqs"; | |
import * as iam from "@aws-cdk/aws-iam"; | |
import * as apig from "@aws-cdk/aws-apigatewayv2"; | |
export default class MyStack extends sst.Stack { | |
constructor(scope, id, props) { | |
super(scope, id, props); | |
const {table} = props; | |
const deadLetterQueue = new sqs.Queue(this, "DeadLetterQueue"); | |
const mainQueue = new sqs.Queue(this, "MainQueue", { | |
deadLetterQueue: { | |
maxReceiveCount: 1, | |
queue: deadLetterQueue | |
} | |
}); | |
const webhookQueue = new sst.Queue(this, "WebhookQueue", { | |
consumer: { | |
handler: "src/strava/webhook_event_processor.handler", | |
environment: { | |
tableName: table.tableName, | |
region: table.env.region | |
} | |
}, | |
sqsQueue: mainQueue | |
}); | |
webhookQueue.attachPermissions(["dynamodb"]); | |
const credentialsRole = new iam.Role(this, "Role", { | |
assumedBy: new iam.ServicePrincipal("apigateway.amazonaws.com") | |
}); | |
credentialsRole.attachInlinePolicy( | |
new iam.Policy(this, "SendMessagePolicy", { | |
statements: [ | |
new iam.PolicyStatement({ | |
actions: ["sqs:SendMessage"], | |
effect: iam.Effect.ALLOW, | |
resources: [mainQueue.queueArn] | |
}) | |
] | |
}) | |
); | |
const api = new apig.HttpApi(this, "webhook-api"); | |
const sqsIntegration = new apig.CfnIntegration(this, "sqsIntegration", { | |
apiId: api.httpApiId, | |
integrationSubtype: "SQS-SendMessage", | |
integrationType: "AWS_PROXY", | |
payloadFormatVersion: "1.0", | |
passthroughBehavior: "WHEN_NO_TEMPLATES", | |
credentialsArn: credentialsRole.roleArn, | |
requestParameters: { | |
QueueUrl: mainQueue.queueUrl, | |
MessageBody: `$request.body` | |
} | |
}); | |
new apig.CfnRoute(this, "webhook", { | |
apiId: api.httpApiId, | |
routeKey: "POST /webhook", | |
target: `integrations/${sqsIntegration.ref}` | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment