Search code examples
aws-cdkjsonpathaws-step-functions

How can I get my entire InputPath as my Payload while also injecting a new field?


In another question, I asked how I can include the executionId of a step function workflow as part of the input to my Lambda function, and this was the solution:

new tasks.LambdaInvoke(this, "InvokeLambdaTask", {
  lambdaFunction: myLambda,
  payload: sfn.TaskInput.fromObject({
    executionId: sfn.JsonPath.stringAt("$$.Execution.Id"),
  }),
})

This works wonderfully.

However, previously, I was leaving my payload unspecified, so I would get my entire InputPath as the payload. I would like to still have my entire InputPath as my payload, but with the addition of the executionId.

I am trying to avoid redundantly specifying each field,

new tasks.LambdaInvoke(this, "InvokeLambdaTask", {
  lambdaFunction: myLambda,
  payload: sfn.TaskInput.fromObject({
    executionId: sfn.JsonPath.stringAt("$$.Execution.Id"),
    foo: sfn.JsonPath.stringAt("$.foo"),
    bar: sfn.JsonPath.stringAt("$.bar"),
    ...
  }),
})

I'm not sure how to express this in CDK/JsonPath in a concise way. I've tried a variety of approaches based on answers to related questions that don't work and probably don't even make sense, like ".$": sfn.JsonPath.stringAt("$")


Solution

  • I don't think it is possible to have all the fields of your InputPath at the same level as the injected field, but you can inject the whole thing as a nested JSON object using objectAt("$").

    For example:

    new tasks.LambdaInvoke(this, "InvokeLambdaTask", {
      lambdaFunction: myLambda,
      payload: sfn.TaskInput.fromObject({
        executionId: sfn.JsonPath.stringAt("$$.Execution.Id"),
        inputPath: sfn.JsonPath.objectAt("$"),
      }),
    })
    

    Then you just need to refactor your Lambda function to accept the input in this format. For example, my lambda, which is in Kotlin:

    data class InputPath(val foo: String, val bar: String)
    
    data class Payload(val executionId: String, val inputPath: InputPath)
    
    ...
        override fun handleRequest(event: Payload, context: Context?) = ...