如何操作 AWS AppSync 和 GraphQL 以符合 DynamoDB 最佳实践?

hga*_*ale 5 amazon-web-services amazon-dynamodb graphql aws-appsync aws-amplify

DynamoDB 在每个应用程序一个表的情况下运行效果最佳 ( https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-nosql-design.html ),但 AppSync 默认情况下打破了该规则从 GraphQL 模式自动生成代码(AWS 建议用户允许 API 执行此操作)。因此,要在坚持 DynamoDB 最佳实践的同时将 AppSync 与 GraphQL 结合使用(假设 DynamoDB 是 GraphQL API 的唯一数据源),这种方法是否有效?

首先,创建一个空白 DynamoDB 表(TheTable在此示例中)并为其指定分区键 ( partitionKey) 和排序键 ( sortKey)。

其次,手动强制每个 GraphQL 类型都由该表支持 ( TheTable)。这就是 AppSync 自动代码生成将走向另一个方向的地方。

GraphQL 架构:

type Pineapple {
    partitionKey: String!
    sortKey: String!
    name: String!
}

# create varying types as long as they all map to the same table
type MachineGun {
    partitionKey: String!
    sortKey: String!
    name: String!
}

input CreatePineappleInput {
    partitionKey: String!
    sortKey: String!
    name: String!
}

type Mutation {
    createPineapple(input: CreatePineappleInput!): Pineapple
}
Run Code Online (Sandbox Code Playgroud)

第三,配置您自己的解析器来处理架构(再次避免自动生成的代码):

解析器:

{
    "version" : "2017-02-28",
    "operation" : "PutItem",
    "key" : {
        "partitionKey": $util.dynamodb.toDynamoDBJson($ctx.args.input.partitionKey),
        "sortKey": $util.dynamodb.toDynamoDBJson($ctx.args.input.sortKey),
    },
    "attributeValues" : $util.dynamodb.toMapValuesJson($ctx.args.input),
}
Run Code Online (Sandbox Code Playgroud)

当我们在 AppSync 控制台中运行突变时:

GraphQL 操作:

mutation createPineapple($createPineappleInput: CreatePineappleInput!) {
  createPineapple(input: $createPineappleInput) {
    name
  }
}

{
  "createPineappleInput": {
    "partitionKey": "attraction123",
    "sortKey": "meta",
    "name": "Looking OK"
  }
}
Run Code Online (Sandbox Code Playgroud)

我们得到了我们希望的结果:

{
  "data": {
    "createPineapple": {
      "name": "Looking OK"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

使用 AppSync 无法实现单表效率是否有原因?

Tin*_*nou 0

我不确定这个说法是否属实

DynamoDB 在每个应用程序使用单个表时运行效果最佳

你介意分享一下你在哪里看到的吗?如果表架构是基于应用程序访问模式构建的,那么 DynamoDB 确实能发挥最佳性能。这并不一定意味着您必须将所有内容都放入一张表中。