Appsync Resolver UpdateItem 忽略空参数?

Appsync Resolver UpdateItem ignore null args?

我正在我的 Appsync 解析器中执行此操作:

{
    "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}" },
        }
    }
}

但有时我可能不会同时输入名称和描述。当这些参数为空时,我如何让它不设置这些列?

这很有可能。您只需添加一个简单的 if 语句来检查该值是否存在。可以在此处的文档中看到一个平行示例:https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-resolvers.html

具体来说,该示例(下方)将可选参数应用到列表操作中。

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

只需应用 if 的 null 检查就可以为您工作。

您需要做的就是根据需要创建自己的 SET expressioncondition checked。下面的表达式检查是否有任何参数是 null or empty,我不想更新它。

#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)
    }
}

希望有用!