如何从数据加载器返回数组?

jha*_*amm 2 graphql graphql-js

这是我的 GraphQL 类型:

const PoliticalEntity = new GraphQLObjectType({
    name: 'PoliticalEntity',
    fields: () => ({
        id: {
            type: GraphQLID,
            resolve: obj => obj.political_entity_id
        },
        algorithmValues: {
            type: new GraphQLList(AlgorithmValue),
            resolve: (obj, args, context) => {
                context
                    .dataloaders
                    .algorithmValueLoader
                    .load(obj.political_entity_id)
            }
        }
    })
});
Run Code Online (Sandbox Code Playgroud)

对于每个PoliticalEntity我有多个AlgorithmValues. 如何让数据加载器为每个键返回多个值?

正在调用数据加载器并且查询正在正确返回,但我仍然收到错误。 DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.

我该如何解决?

Dan*_*den 5

你的批量加载函数应该返回一个包含数组的 Promise。正如错误所示,传递给批量加载函数的键的长度必须与该结果数组的长度匹配。如果您的 Loader 为每个键获取一个项目数组,那么 Promise 必须解析为一个数组数组。

const backLoadFn = (keys) => {
  return Promise.all(keys.map(key => {
    return Model.findAll({ where: { key } })
  }))
}
Run Code Online (Sandbox Code Playgroud)