Jeff Gu Kang
Jeff Gu Kang

Reputation: 4879

Adding timestamp automatically through AWS Appsync resolver with Dynamodb

I tried to add timestamp automatically when I create some post. But it is not working the example of appsync resolver-context-reference.

https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference.html#time-helpers-in-util-time

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key": {
        "id" : $util.dynamodb.toDynamoDBJson($util.autoId())
    },

    #set( $myfoo = $util.dynamodb.toMapValues($ctx.args) )
    #set( $myFoo.version = $util.dynamodb.toNumber(1) )
    #set( $myFoo.timestamp = $util.time.nowISO8601() )

    "attributeValues" : $util.toJson($myFoo)
}

Upvotes: 5

Views: 4581

Answers (3)

hatboyzero
hatboyzero

Reputation: 1937

Change your resolver to the following

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key": {
        "id" : $util.dynamodb.toDynamoDBJson($util.autoId())
    },

    #set( $myFoo = $util.dynamodb.toMapValues($ctx.args) )
    #set( $myFoo.version = $util.dynamodb.toNumber(1) )
    #set( $myFoo.timestamp = $util.dynamodb.toDynamoDB($util.time.nowISO8601()) )

    "attributeValues" : $util.toJson($myFoo)
}

Also note the call to $util.time.nowISO8601() is now wrapped with $util.dynamodb.toDynamoDB()

Upvotes: 5

Jeff Gu Kang
Jeff Gu Kang

Reputation: 4879

For dynamoDB, String should change to dynamodb type through $util. Thus, it would be work after changing time string to dynamoDB type.

#set( $myFoo.timestamp = $util.time.nowISO8601() )
=>  
#set( $myFoo.timestamp = $util.dynamodb.toDynamoDB($util.time.nowISO8601())

Upvotes: 1

Vladimir
Vladimir

Reputation: 2553

This is a working example of what you're looking to do (taken from my AppSync API resolver). Note the "messageId" and "createdDate" attributes. That's how you can add a date while writing to DDB.

{
  "version": "2017-02-28",
  "operation": "PutItem",
  "key": {
    "eventId": $util.dynamodb.toDynamoDBJson($ctx.args.input.eventId),
    "messageId": $util.dynamodb.toDynamoDBJson("$util.time.nowISO8601()$util.autoId()"),
  },
  "attributeValues": {
    "message": $util.dynamodb.toDynamoDBJson($ctx.args.input.message),
    "createdDate": $util.dynamodb.toDynamoDBJson($util.time.nowISO8601())
  }
}

Upvotes: 7

Related Questions