【问题标题】:How to use custom input types in AppSync GraphQL schema?如何在 AppSync GraphQL 架构中使用自定义输入类型?
【发布时间】:2021-03-10 09:55:32
【问题描述】:

我正在试验 AppSync + DynamoDB。我想在我的 GraphQL Schema 中有以下类型:

type User {
    user_id: String!
}

type Box {
    name: String!
    user: User!

}

如何在 DynamoDB 中创建一个存储指向另一个表的项目的表(在我的情况下,我希望表 BoxTable 的字段 user 成为表 UserTable 中用户的引用?

如何在 AppSync 中定义上述架构?当我设置user: User! 时,我收到错误Expected User! to be a GraphQL input type.?

【问题讨论】:

    标签: graphql amazon-dynamodb aws-appsync


    【解决方案1】:

    根据我对您问题的理解,这些是我的答案。

    如何在 DynamoDB 中创建一个表来存储指向另一个表的项目

    DynamoDB 不是关系数据库,不提供外键或表连接。因此,要实现您在帖子中提到的内容,您仍然需要两次调用 DynamoDB 来获取 Box 的所有信息,即首先从 BoxTable 获取 Box 项目,然后从 @ 获取 user 987654325@ 基于user_id。如果您的用例是您首先获得user,那么您可以使用user_id 的过滤器获得Box

    现在到您帖子的第二部分,

    如何在 AppSync 中定义上述架构?

    使用 DynamoDB 单元解析器,您可以查询单个表(在 DynamoDB 批量操作之外,但这些是为批量用例保留的)。

    这样做的一种方法是定义应该看起来像这样的架构;

    type User {
        user_id: String!
    }
    
    type Box {
        name: String!
        user: User!
    }
    
    input BoxInput {
        name: String!
        user: UserInput!
    }
    
    input UserInput {
        user_id: String!
    }
    
    type Mutation {
        createBox(input: BoxInput): Box
    }
    
    type Query {
        getBox(input: BoxInput): Box
    }
    

    这就是您可以运行查询和变异的方式;

    mutation createBox {
            createBox(input: {
                name: "abc"
                user: { user_id: "1234-abcd-5678-efgh"}
            }){
                name
                user { user_id }
            }
        }
    
    query getBox {
            getBox(input: {
                name: "abc"
                user: { user_id: "1234-abcd-5678-efgh"}
            }){
                name
                user { user_id }
            }
        }
    

    因此,请注意上述查询和变异。这些会将user 显示为空,除非您在Box 类型中附加一个单独的解析器与user 类型。例如:

    Query that returns Box --> Resolver
    
    type Box {
        name
        user --> Attach resolver to get user_id from your UserTable
    }
    

    另一种方法是利用管道解析器,您可以在其中创建多个函数,每个函数都可以使用前一个函数的结果并查询数据库。这些函数按照您指定的顺序运行。例如:

    1. BoxTable获取Box的函数。
    2. 通过使用来自ctx.prev.resultuser_idUserTable 获取user 的函数。
    3. 最后根据架构中的 Box 类型将上述两个结果合并为一个 JSON 对象。

    【讨论】:

      猜你喜欢
      • 2020-05-19
      • 2020-04-20
      • 2020-03-21
      • 2021-03-28
      • 2019-04-15
      • 2020-05-05
      • 2019-04-03
      • 2017-06-04
      • 2020-11-09
      相关资源
      最近更新 更多