【发布时间】:2020-01-17 19:26:32
【问题描述】:
我正在尝试与 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;
};
我在加载多个 PurchaseOrder 时遇到以下问题:
在 DataLoader 的 ids 参数中多次调用单个 customer_id。因此,一个示例 id
5cee853eae92f6021f297f45在对我的加载程序的多个请求中被调用,在连续调用中。这表明缓存无法正常工作。我在处理读取结果时发现的变量总是设置为 false,即使比较正确的 id。
【问题讨论】:
标签: javascript mongodb mongoose graphql dataloader