2

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

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

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

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

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

感谢帮助

4

1 回答 1

0

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

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

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解析的全部返回值。所以在这里我可以根据我得到的用户 ID 来获取所有的朋友source

希望能帮助到你。

于 2018-07-06T10:16:01.867 回答