Appsync dynamodb 请求映射 - 默认变量



如果没有提供查询中的变量之一,我正在寻找一种为 appsync dynamodb 解析器设置默认变量的方法。假设我们有简单的数据库请求映射

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key" : {
        ## If your table's hash key is not named 'id', update it here. **
        "id" : { "S" : "$utils.autoId()" }
    },
    "attributeValues" : {
        ## Add an item for each field you would like to store to Amazon DynamoDB. **
        "key" : { "S" : "${context.arguments.id}" },
        "name" : { "S" : "${context.arguments.name}" }
    }
}

我找到了一种使用条件语句来做到这一点的方法

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key" : {
        ## If your table's hash key is not named 'id', update it here. **
        "id" : { "S" : "$utils.autoId()" }
    },
    "attributeValues" : {
        ## Add an item for each field you would like to store to Amazon DynamoDB. **
        "key" : { "S" : "${context.arguments.id}" },
        #if( ($context.arguments.name))
            "name" : { "S" : "${context.arguments.name}" }
        #else
            "name" : { "S" : "default" }
        #end
    }
}

上述方式,如果没有提供,我们也可以排除其中一个属性

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key" : {
        ## If your table's hash key is not named 'id', update it here. **
        "id" : { "S" : "$utils.autoId()" }
    },
    "attributeValues" : {
        ## Add an item for each field you would like to store to Amazon DynamoDB. **
        "key" : { "S" : "${context.arguments.id}" },
        #if( ($context.arguments.name))
            "name" : { "S" : "${context.arguments.name}" }
        #end
    }
}

如果未提供$context.arguments.name则名称属性不会插入到 dynamodb 中。但是上面有什么更聪明的方法吗?

如果您不想显式指定键,可以执行以下操作:

{
"version" : "2017-02-28",
"operation" : "PutItem",
"key" : {
    ## If your table's hash key is not named 'id', update it here. **
    "id" : { "S" : "$utils.autoId()" }
},
#set( $expValues = {} )
#foreach( $entry in $context.arguments.entrySet() )
$!{expValues.put("${entry.key}", { "S" : "${entry.value}" })}
#end
#if( !${expValues.isEmpty()} )
"attributeValues" : $utils.toJson($expValues)
#end
}

最新更新