5

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)
}
Jeff Gu Kang
  • 4,749
  • 2
  • 36
  • 44

3 Answers3

7

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())
  }
}
Vladimir
  • 2,481
  • 4
  • 31
  • 41
  • Is it work correctly as `"$util.time.nowISO8601()$util.autoId()"`? – Jeff Gu Kang May 14 '18 at 03:22
  • Yes. You can use additional values for sorting and range purposes as well. Up to you. Here's a good guide to follow: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html – Vladimir May 14 '18 at 14:26
  • I was strugging on how to pass the current itmestamp to dynamodb to fetch a result and found this post and used this --> $util.dynamodb.toDynamoDBJson($util.time.nowISO8601()) and it worked like charm. Thanks for the code snippet. You saved my day. – Suvoraj Biswas Aug 25 '20 at 11:24
5

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()

pauldendulk
  • 1,378
  • 12
  • 23
hatboyzero
  • 1,929
  • 1
  • 21
  • 44
1

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())
Jeff Gu Kang
  • 4,749
  • 2
  • 36
  • 44