I get conditional exception even though the request meets condition in AppSync

84 views Asked by At

Overview

I am quite new to AppSync.

Issue

I could not limit PutItem command even though I set a condition in resolver.

Query

mutation MyMutation {
  createTodo(input: {description: "test", name: "test2"}) {
    id
    description
    name
  }
}

Result

{
  "data": {
    "createTodo": null
  },
  "errors": [
    {
      "path": [
        "createTodo"
      ],
      "data": null,
      "errorType": null,
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "The conditional request failed (Service: DynamoDb, Status Code: 400, Request ID: XXX"
    }
  ]
}

Resolver

{
  "operation": "PutItem",
  "key": {
    "id": $util.dynamodb.toDynamoDBJson($util.autoId())
  },
  "attributeValues" : {
        "name"    : $util.dynamodb.toDynamoDBJson($ctx.args.input.name),
        "description"    : $util.dynamodb.toDynamoDBJson($ctx.args.input.description)
  },
  "condition": {
    "expression": "description = :sizeValue",
    "expressionValues": {
      ":sizeValue": {
        "S":"test"
      }
    }
  }
}

In above example, I set "test" in description. So, I think there should be no conditional exception. However, I get error message saying "The conditional request failed".

I checked the CloudWatch log.

"transformedTemplate": "{\n  \"operation\": \"PutItem\",\n  \"key\": {\n    \"id\": {\"S\":\"xxx\"}\n  },\n  \"attributeValues\" : {\n        \"name\"    : {\"S\":\"test2\"},\n        \"description\"    : {\"S\":\"test\"}\n  },\n  \"condition\": {\n    \"expression\": \"description = :sizeValue\",\n\t\"expressionValues\": {\n      \":sizeValue\": {\n        \"S\":\"test\"\n      }\n    }\n  }\n}"
}

↓ (After formatting)

{
  "operation": "PutItem",
  "key": {
    "id": {"S":"xxx"}
  },
  "attributeValues" : {
        "name"    : {"S":"test2"},
        "description"    : {"S":"test"}
  },
  "condition": {
    "expression": "description = :sizeValue",
    "expressionValues": {
      ":sizeValue": {
        "S":"test"
      }
    }
  }
}

Based on the above log, I think the request should satisfy the condition.

Does anyone have any ideas about how to solve the issue? Thank you.

1

There are 1 answers

2
Leeroy Hannigan On BEST ANSWER

You have written a PutItem request which states:

Save item "id": {"S":"xxx"} only if the item is already stored in DynamoDB and has a value for description which equals test.

I believe you think the condition is based on what you set for attributes in the request, but conditions are for evaluating items state already stored in DynamoDB.

So in summary, you get a ConditionCheckFailedException because you don't have an item in your DynamoDB table with an id=test2 and description=test. This is what you require for your condition to evaluate to true.