DynamoDB Transactions using CDK with AppSync

Viewed 29

I'm trying to resolve a mutation using DynamoDB as a data source which requires performing transactions on other DynamoDB tables

mutation MyMutation {
  like(tweetId: "0ABCDEFGHIK")
}

Error:

{
  "data": null,
  "errors": [
    {
      "path": [
        "like"
      ],
      "data": null,
      "errorType": null,
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Failed to execute DynamoDB transaction"
    }
  ]
}

i.e when Mutation occurs on my likes table I need to perform writes and updates on my users and tweets table.

As per documentation which states, appync needs to assume the role of performing transactions I have implemented the following constructs

Service role

const likeTableTransactionItemRole = new iam.Role(
  this,
  "likeTableTransactionItemRole",
  {
    assumedBy: new iam.ServicePrincipal("appsync.amazonaws.com"),
  }
);

Attaching Inline Policy( Ps: I'm aware * is bad practice, goal is to get it to work)

likeTableTransactionItemRole.attachInlinePolicy(
  new iam.Policy(this, "likeTableTransactionItemPolicy", {
    statements: [
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ["*"],
        resources: [likesTable.tableArn, likesTable.tableArn + "/*"],
      }),
      new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: ["*"],
        resources: [
          tweetsTable.tableArn,
          tweetsTable.tableArn + "/*",
          usersTable.tableArn,
          usersTable.tableArn + "/*",
        ],
      }),
    ],
  })
);

Creating a DynamDB Data Source for the same

const transactionDataSource = new DynamoDbDataSource(
  this,
  "likesTableTransaction",
  {
    api,
    table: likesTable,
    serviceRole: likeTableTransactionItemRole,
  }
);

Creating a Resolver for the mutation

 const likeMutationResolver = new appsync.Resolver(this, "likes", {
      api,
      typeName: "Mutation",
      fieldName: "like",
      dataSource: transactionDataSource,
      requestMappingTemplate: appsync.MappingTemplate.fromFile(
        path.join(mappingTemplatesLocation, "Mutation.like.request.vtl")
      ),
      responseMappingTemplate: appsync.MappingTemplate.fromFile(
        path.join(mappingTemplatesLocation, "Mutation.like.response.vtl")
      ),
    });

Any leads would be appreciated

0 Answers
Related