Search code examples
amazon-web-servicesamazon-dynamodbaws-appsync

Appsync Resolver UpdateItem ignore null args?


I am doing this in my Appsync Resolver:

{
    "version" : "2017-02-28",
    "operation" : "UpdateItem",
    "key" : {
        "pk" : { "S" : "Container" },
        "id" : { "S" : "${ctx.args.id}" }
    },
    "update" : {
        "expression" : "SET #name = :name, description = :description",
        "expressionNames": {
            "#name" : "name"
        },
        "expressionValues": {
            ":name" : { "S": "${context.arguments.name}" },
            ":description" : { "S": "${context.arguments.description}" },
        }
    }
}

But sometimes I may not pass in both name and description. How would I make it not SET those columns when those args are null?


Solution

  • All you need to do is to create your own SET expression with condition checked based on your need. Below expression check if any argument is null or empty, I don't want to update it.

    #set( $expression = "SET" )
    #set( $expValues = {} )
    
    ## NAME
    #if( !$util.isNullOrEmpty(${context.arguments.name}) )
        #set( $expression = "${expression} name = :name" )
        $!{expValues.put(":name", { "S" : "${context.arguments.name}" })}
    #end
    
    ## DESCRIPTION
    #if( !$util.isNullOrEmpty(${context.arguments.description}) ) 
        #if( ${expression} != "SET" ) 
            #set( $expression = "${expression}," )
        #end
        #set( $expression = "${expression} description = :description" )
        $!{expValues.put(":description", { "S" : "${context.arguments.description}" })}
    #end
    
    {
        "version" : "2017-02-28",
        "operation" : "UpdateItem",
        "key" : {
            "pk" : { "S" : "Container" }
            "id" : { "S" : "${context.arguments.id}" }
        },
        "update" : {
            "expression" : "${expression}",
            "expressionValues": $util.toJson($expValues)
        }
    }
    

    Hope it is useful!