aws / aws-appsync-community

The AWS AppSync community
https://aws.amazon.com/appsync
Apache License 2.0
506 stars 32 forks source link

AppSync DynamoDB Resolvers with update conditions #228

Open kostyrin opened 2 years ago

kostyrin commented 2 years ago

There is a resolver's code

{
  "version": "2017-02-28",
  "operation": "UpdateItem",
  "key": {
    "PK": $util.dynamodb.toDynamoDBJson($ctx.args.input.PK),
    "SK": $util.dynamodb.toDynamoDBJson($ctx.args.input.SK),
  },

    ## Set up some space to keep track of things you're updating **
    #set( $expNames  = {} )
    #set( $expValues = {} )
    #set( $expSet = {} )
    #set( $expAdd = {} )

    ## Increment "ActualLimit" 
    $!{expAdd.put("ActualLimit", ":actuallimit")}
    $!{expValues.put(":actuallimit", { "N" : $context.arguments.input.ActualLimit } )}

    ## Continue building the update expression, adding attributes you're going to ADD **
    #if( !${expAdd.isEmpty()} )
        #set( $expression = "${expression} ADD" )
        #foreach( $entry in $expAdd.entrySet() )
            #set( $expression = "${expression} ${entry.key} ${entry.value}" )
            #if ( $foreach.hasNext )
                #set( $expression = "${expression}," )
            #end
        #end
    #end

    ## Finally, write the update expression into the document, along with any expressionNames and expressionValues **
    "update" : {
        "expression" : "${expression}"
        #if( !${expNames.isEmpty()} )
            ,"expressionNames" : $utils.toJson($expNames)
        #end
        #if( !${expValues.isEmpty()} )
            ,"expressionValues" : $utils.toJson($expValues)
        #end
    },

    "condition" : {
        "expression"       : "LimitDate = :expectedLimitDate",
        "expressionValues" : {
            ":expectedLimitDate" : $util.dynamodb.toDynamoDBJson($context.arguments.input.LimitDate)
        }
    }

}

and mutation:

mutation MyMutation {
  update(input: {PK: "pk1", SK: "sk1", ActualLimit:0, LimitDate: "YYYY-MM-DD"}) {
    ActualLimit CreatedAt LimitDate
  }
}

where PK - primary key, SK - sorted key, ActualLimit is integer value, LimitDate is string value.

My question is how to write the code if I need two cases:

e.g.: have record in DynamoDb: { "PK": "pk1", "SK": "sk1", "ActualLimit": 10, "LimitDate": "2022-06-08"} case 1:

mutation MyMutation {
  update(input: {PK: "pk1", SK: "sk1", ActualLimit:2, LimitDate: "2022-06-08"}) {
    ActualLimit CreatedAt LimitDate
  }
}

then have record in DynamoDb: { "PK": "pk1", "SK": "sk1", "ActualLimit": 12, "LimitDate": "2022-06-08"}

case 2:

mutation MyMutation {
  update(input: {PK: "pk1", SK: "sk1", ActualLimit:1, LimitDate: "2022-06-19"}) {
    ActualLimit CreatedAt LimitDate
  }
}

then have record in DynamoDb: { "PK": "pk1", "SK": "sk1", "ActualLimit": 1, "LimitDate": "2022-06-19"}

How to do that? thanks.