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

时间:2019-05-27 18:53:34

标签: 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)
            }
        }
    })
});

对于每个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.

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您的批处理加载函数应返回带有数组的Promise。如错误所示,传递给批处理加载函数的键的长度必须与该结果数组的长度匹配。如果您的加载程序正在为每个键获取项目数组,则Promise必须解析为数组数组。

const backLoadFn = (keys) => {
  return Promise.all(keys.map(key => {
    return Model.findAll({ where: { key } })
  }))
}