Appsync Resolver UpdateItem ignore null args?

Viewed 1521

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?

2 Answers

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!

This is very much possible. You just have to add a simple if statement to check if the value is there. A parallel example can be seen in the docs here: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers.html

Specifically, that example (below) uses the application of optional arguments into a list operation.

{ "version" : "2017-02-28", "operation" : "Scan" #if( ${context.arguments.count} ) ,"limit": ${context.arguments.count} #end #if( ${context.arguments.nextToken} ) ,"nextToken": "${context.arguments.nextToken}" #end }

Just applying that if's null check should work for you.

Related