Skip to content

Instantly share code, notes, and snippets.

@leegilmorecode
Last active July 31, 2022 06:41
Show Gist options
  • Save leegilmorecode/3667c6a1cf8e8f33f16c1c5b72ca654e to your computer and use it in GitHub Desktop.
Save leegilmorecode/3667c6a1cf8e8f33f16c1c5b72ca654e to your computer and use it in GitHub Desktop.
Example of invoking a Step Function Express Workflow from Amazon API Gateway
// create the state machine defintion for cancelling an order
const cancelOrderStateMachineDefinition: sfn.TaskStateBase =
new tasks.LambdaInvoke(this, "CancelOrder", {
lambdaFunction: cancelOrderHandler,
resultPath: "$",
timeout: Duration.seconds(30),
comment: "Cancel order task",
retryOnServiceExceptions: true,
}).addCatch(
new tasks.SqsSendMessage(this, "SendSQSFailure", {
queue: new sqs.Queue(this, "CancelOrderLambdaFailureDLQ", {
queueName: "cancel-order-lambda-failure-dlq",
}),
messageBody: sfn.TaskInput.fromJsonPathAt(
"States.StringToJson($.Cause)"
),
})
);
// create the state machine for cancelling orders
const cancelOrderStateMachine: sfn.StateMachine = new sfn.StateMachine(
this,
"CancelOrderStateMachine",
{
definition: cancelOrderStateMachineDefinition,
logs: {
level: sfn.LogLevel.ALL,
destination: new logs.LogGroup(
this,
"cancelOrderStateMachineLogGroup",
{
retention: logs.RetentionDays.ONE_DAY,
}
),
includeExecutionData: true,
},
tracingEnabled: true,
stateMachineName: "CancelOrderStateMachine",
stateMachineType: sfn.StateMachineType.EXPRESS,
timeout: Duration.seconds(30),
}
);
// create the orders resource
const orders: apigw.Resource = onlineOrdersApi.root.addResource("orders");
// create the role for invoking the step function
const apigwRole: iam.Role = new iam.Role(this, "OnlineOrdersRole", {
assumedBy: new iam.ServicePrincipal("apigateway"),
inlinePolicies: {
putEvents: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
actions: ["events:PutEvents"],
resources: [eventBus.eventBusArn],
}),
new iam.PolicyStatement({
actions: ["states:StartSyncExecution"],
effect: iam.Effect.ALLOW,
resources: [cancelOrderStateMachine.stateMachineArn],
}),
],
}),
},
});
// step function options for the api gateway integration
const stepFunctionOptions: apigw.IntegrationOptions = {
credentialsRole: apigwRole,
integrationResponses: [
{
statusCode: "200",
responseTemplates: {
"application/json": "Cancelled",
},
},
],
passthroughBehavior: apigw.PassthroughBehavior.NEVER,
requestTemplates: {
"application/json": `{
"input": "{\\"actionType\\": \\"cancel\\", \\"body\\": $util.escapeJavaScript($input.json('$'))}",
"stateMachineArn": "${cancelOrderStateMachine.stateMachineArn}"
}`,
},
};
// the cancel order endpoint persists a message directly with state machine
orders.addMethod(
"PUT",
new apigw.Integration({
type: apigw.IntegrationType.AWS,
uri: `arn:aws:apigateway:${cdk.Aws.REGION}:states:action/StartSyncExecution`,
integrationHttpMethod: "POST",
options: stepFunctionOptions,
}),
{ methodResponses: [{ statusCode: "200" }] }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment