从字段解析器上的父节点获取数据

Get data from parent node on field resolver

因此,如果可能的话,我正在尝试制作这样的 GraphQL

{
  people {
    _id
    name
    acted {
      _id
      title
      coactors {
        name
      }
    }
  }
}

所以我正在做的,就是找演员(人),然后拍他们演的电影,效果很好。所以我想找那部电影的合作演员。我正在考虑将当前演员的 ID 作为这样的参数传递给合作演员字段:

{
  people {
    _id
    name
    acted {
      _id
      title
      coactors(actor: people._id) {
        name
      }
    }
  }
}

显然,我遇到了一个错误,不知道是否可以在内部进行。

这是我的类型:

const MovieType = new GraphQLObjectType({
    name: 'movie',
    fields: () => ({
        _id: {
            type: GraphQLInt
        },
        title: {
            type: GraphQLString
        },
        tagline: {
            type: GraphQLString
        },
        released: {
            type: GraphQLInt
        },
        actors: {
            type: new GraphQLList(PersonType),
            resolve: (movie) => {
                return [];
            }
        },
        coactors: {
            type: new GraphQLList(PersonType),
            args: {
                actor: {
                    type: GraphQLInt
                }
            },
            resolve: (movie, args) => {
                getCoActorsFor(movie, args.actor) // How can I do something like this
                    .then((actors) => {
                        return actors;
                    })
            }
        }
    })
});

const PersonType = new GraphQLObjectType({
    name: 'person',
    fields: ()=> ({
        _id: {
            type: GraphQLInt
        },
        name: {
            type: GraphQLString
        },
        born: {
            type: GraphQLInt
        },
        acted: {
            type: new GraphQLList(MovieType),
            resolve: (person) => {

                return [];

            }
        }
    })
});

如果不将查询分成两个查询,这是不可能的,因此您将第一个查询的结果作为变量提供给参与者,以提供给第二个查询。

您可以让 return 由 "acted" 编辑的电影对象包含对演员的引用,而不是使用变量,而不是当您要求 "coactors" 时您拥有手头的信息来做你想做的事。

然而,这种类型的 API 也是一种反模式 - 如果子对象依赖于父对象的上下文,那么缓存和理解就会困难得多。我认为您应该问问自己,为什么 Movie 对象除了演员之外还必须 return 共同演员。如果 coactors 只是相同的 actor 列表,但删除了原始 actor,这似乎很容易发生在客户端,因为上下文信息更容易获得。