How to autogenerate global ID using AppSync + DynamoDB

How do I generate ID automatically when I use AppSync and DynamoDB as the database source?

I have a type looking like below

type Post {
    id: ID!
    creator: String!
    createdAt: String!
    like: Int!
    dislike: Int!
    frozen: Boolean!
}

and input looking like below

input CreatePostInput {
    id: ID!
    creator: String!
    createdAt: String!
    like: Int!
    dislike: Int!
    frozen: Boolean!
}

and my mutation is obviously the combination of the two

createPost(input: CreatePostInput!): Post

However, when I make inserts I have to do something like below

mutation createPost{
  createPost(input:{
    id:2
    creator:"some creator"
    createdAt:"some date"
    like:0
    dislike:0
    frozen:false
  }){
    id
    creator
    createdAt
    like
    dislike
    frozen
  }
}

There is no way I can insert a post without having to know what the id is up to right now. Is there a way I can provide null or any random id and DynamoDB or AppSync automatically create the next index before inserting into the table?

1 answer

  • answered 2018-07-12 13:19 mparis

    You can auto generate a UUIDv4 using the $util.autoId() velocity helper function. For example, you can write a createPost resolver that uses a server-side generated id like this.

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