1
votes

I'm looking a way for setting default variables for appsync dynamodb resolvers, if one of variables from query is not provided. Let's say we have simple db request mapping

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

I found a way to do this using conditional statements

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

Above way we can also exclude one of attributes if it is not provided

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

If $context.arguments.name is not provided then name attribute isn't inserted into dynamodb. But is there any smarter way to do above?

1

1 Answers

1
votes

If you don't want to specify keys explicitly, you can do something like:

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