Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}
like image 640
Jeff Gu Kang Avatar asked Dec 17 '22 23:12

Jeff Gu Kang


2 Answers

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())
  }
}
like image 199
Vladimir Avatar answered May 05 '23 10:05

Vladimir


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

like image 41
hatboyzero Avatar answered May 05 '23 10:05

hatboyzero