当使用AppSync和DynamoDB时,可以使用$util.autoId()函数来生成唯一的ID。这个函数会生成一个随机的UUID。在DynamoDB中,可以使用分区键和排序键来设计数据模型。
下面是一个代码示例,演示了如何在AppSync和DynamoDB中使用$util.autoId()函数以及如何设计分区键和排序键:
type Mutation {
createObject(input: CreateObjectInput!): Object
}
input CreateObjectInput {
name: String!
}
type Object {
id: ID!
name: String!
}
#set($id = $util.autoId())
$util.qr($ctx.args.input.put("id", $id))
$util.qr($ctx.stash.put("id", $id))
{
"version": "2017-02-28",
"operation": "PutItem",
"key": {
"id": $util.dynamodb.toDynamoDBJson($id)
},
"attributeValues": $util.dynamodb.toMapValuesJson($ctx.args.input),
"condition": {
"expression": "attribute_not_exists(id)"
}
}
Table name: MyTable
Partition key: id (String)
Sort key: name (String)
通过上述步骤,你可以使用$util.autoId()函数生成唯一的ID,并将数据保存到DynamoDB中。同时,通过设计合理的分区键和排序键,可以提高查询性能,便于按需检索数据。
这只是一个简单的示例,实际的数据模型设计可能更加复杂,取决于你的业务需求。你可以根据具体情况进行适当调整和扩展。