0

我正在尝试与 Mongoose 一起构建 DataLoader 的以下用例:

export const PurchaseOrderType = new GraphQLObjectType({
    name: "PurchaseOrder",
    description: "PurchaseOrder",
    interfaces: () => [NodeInterface],
    isTypeOf: value => value instanceof PurchaseOrderModel,
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLID),
            resolve: obj => dbIdToNodeId(obj._id, "PurchaseOrder")
        },
        name: {
            type: new GraphQLNonNull(GraphQLString)
        },
        customer: {
            type: CustomerType,
            resolve: (source, args, context) => {
                return context.customerLoader.load(source.customer_id);
            }
        }
    })
});

export default () => {
    return graphqlHTTP((req, res, graphQLParams) => {
        return {
            schema: schema,
            graphiql: true,
            pretty: true,
            context: {
                customerLoader: customerGetByIdsLoader()
            },
            formatError: error => ({
                message: error.message,
                locations: error.locations,
                stack: error.stack,
                path: error.path
            })
        };
    });
};



export const customerGetByIdsLoader = () =>
    new DataLoader(ids => {
        return customerGetByIds(ids);
    });


export const customerGetByIds = async ids => {
    let result = await Customer.find({ _id: { $in: ids }, deletedAt: null }).exec();

    let rows = ids.map(id => {
        let found = result.find(item => {
            return item.id.equals(id);
        });

        return found ? found : null; << === found always undefined
    });

    return rows;
};

加载多个采购订单时,我面临以下问题:

  1. 在 DataLoader 的 ids 参数中多次调用单个 customer_id。5cee853eae92f6021f297f45因此,在连续调用中,对我的加载程序的多个请求都调用了一个示例 id 。这表明缓存无法正常工作。

  2. 我在处理读取结果时发现的变量总是设置为 false,即使比较正确的 id。

4

1 回答 1

0

您可以使用 findOne

export const customerGetByIds = async ids => {
   let result = await Customer.find({ _id: { $in: ids }, deletedAt: null }).exec();
   const rows = []
   let promiseAll = ids.map(async (id) => {
      let found = result.filter(item => item.id.toString() === id.toSring());
      if(found) {
         rows.push(found[0])
         return found[0] 
      }
      return null; 
   });
   await Promise.all(promiseAll);
   return rows;
};
于 2019-09-17T11:37:32.463 回答