如何使用 AppSync + DynamoDB 自动生成全局 ID

How to autogenerate global ID using AppSync + DynamoDB

当我使用AppSyncDynamoDB作为数据库源时,如何自动生成ID?

我的类型如下所示

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

输入如下所示

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

而我的变异显然是两者的结合

createPost(input: CreatePostInput!): Post

但是,当我进行插入时,我必须执行如下操作

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

我无法插入 post 而不必知道 id 现在在做什么。有没有一种方法可以提供 null 或任何随机 idDynamoDBAppSync 在插入 table 之前自动创建下一个索引?

Error generated when I update the input CreatePostInput to not accept any ID

{
  "data": {
    "createPost": null
  },
  "errors": [
    {
      "path": [
        "createPost"
      ],
      "data": null,
      "errorType": "DynamoDB:AmazonDynamoDBException",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "One or more parameter values were invalid: Type mismatch for key id expected: S actual: NULL (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 629QEM7MH9BRAJ9MHU3FM1S0U3VV4KQNSO5AEMVJF66Q9ASUAAJG)"
    }
  ]
}

My Resolver Template

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key" : {
        ## If object "id" should come from GraphQL arguments, change to $util.dynamodb.toDynamoDBJson($ctx.args.id)
        "id": $util.dynamodb.toDynamoDBJson($util.autoId()),
    },
    "attributeValues" : $util.dynamodb.toMapValuesJson($ctx.args)
}

您可以使用 $util.autoId() velocity 辅助函数自动生成 UUIDv4。例如,您可以编写一个使用服务器端生成的 id 的 createPost 解析器,如下所示。

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

首先,将 createPost 解析器更新为:

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

然后,从您的 CreatePostInput 输入类型中删除 id 字段:

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

保存两个更改,你应该完成了。

如果您是像我一样眼见为实的人,请看一看这个 egghead.io video