【问题标题】:Pass parameters to sub nodes resolvers functions将参数传递给子节点解析器函数
【发布时间】:2017-08-13 07:22:54
【问题描述】:

我有这个 graphql 查询,它查找与项目关联的所有服务(给定它的 id ),并且对于每个服务,它返回有权访问的用户列表。

query Project ($id: ID!) {
  services {
    mailService {
      users
    }
  }
}

我想知道传递id 参数并在users 解析器函数中使用它的最佳解决方案是什么。

我正在考虑这些解决方案:

  • 在查询中为 mailService 和 users 节点添加 $id 参数。
  • 在服务器的graphql中间件中,将参数对象添加到上下文字段(来自request.body)
  • 在项目解析器的上下文对象中添加一个字段:context.projectId = $id 并在子字段解析器中使用它。

感谢您的帮助

【问题讨论】:

  • 为什么您的users 解析器需要知道项目ID?从 API 消费者的角度来看,我觉得这会让人感到困惑。
  • 主要原因是因为我需要调用 2 个不同的 Rest API 来获取项目基本信息并获取有权访问服务的用户列表。第二个 API 有 2 个参数:projectId 和服务标识符。

标签: graphql graphql-js apollo apollo-server


【解决方案1】:

您可以通过对象类型的本地解析来做到这一点。

在子节点的resolve中,可以访问整个父节点的数据。 例如:

export const User: GraphQLObjectType = new GraphQLObjectType({
    name: 'User',
    description: 'User type',
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLID),
            description: 'The user id.',
        },
        name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'The user name.',
        },
        friends: {
            type: new GraphQLList(User),
            description: 'User friends',
            resolve: (source: any, args: any, context: any, info: any) => {
                console.log('friends source: ', source)
                return [
                    {id: 1, name: "friend1"},
                    {id: 2, name: "friend2"},
                ]
            }
        }
    }),
})

const Query = new GraphQLObjectType({
    name: 'Query',
    description: 'Root Query',
    fields: () => ({
        user: {
            type: User,
            description: User.description,
            args: {
                id: {
                    type: GraphQLInt,
                    description: 'the user id',
                }
            },
            resolve: (source: any, args: any, context: any, info: any) => {
                console.log('user args: ', args)
                return { id: 2, name: "user2" }
            }
        }
    })
})

friends 解析中,source 参数具有来自父user 解析的全部返回值。所以在这里我可以根据我从source 获得的用户 ID 获取所有朋友。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 2017-02-05
    • 2019-03-01
    • 2016-08-07
    • 2021-01-07
    • 2018-01-15
    • 2018-03-28
    • 1970-01-01
    • 2015-02-26
    相关资源
    最近更新 更多