使用AppSync
和DynamoDB
作为数据库源时如何自动生成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
}
}
我无需知道
id
目前正在做什么就无法插入帖子。有没有办法我可以提供null
或任何随机的id
和DynamoDB
或AppSync
在插入表之前自动创建下一个索引?{
"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)"
}
]
}
{
"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)
}
最佳答案
首先,将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",
},
},
}
然后,从您的
id
输入类型中删除CreatePostInput
字段:input CreatePostInput {
creator: String!
createdAt: String!
like: Int!
dislike: Int!
frozen: Boolean!
}
保存所有更改,您应该已完成。
如果您是像我这样有见识的人之一,请看看此egghead.io video。
关于amazon-web-services - 如何使用AppSync + DynamoDB自动生成全局ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51299682/