猫鼬:在另一个解析器中调用解析器
Mongoose: call a resolver in another resolver
我有订阅活动的用户:
const EventType = new GraphQLObjectType({
name:'Event',
fields:() => ({
id: {type:GraphQLID}
})
});
const UserType = new GraphQLObjectType({
name:'User',
fields:() => ({
id: {type:GraphQLString},
_subscriptionIds: { type: new GraphQLList(GraphQLID) },
subscriptions: {
type: new GraphQLList(EventType),
async resolve(parent, args) {
return Event.find( {_id: { $in: parent._subscriptionIds}})
}
}
anotherField: {
type: new AnotherType,
async resolve(parent, args) {
console.log(parent.subscriptions) // parent.subscriptions is undefined, I need to resolve it.
}
})
});
长话短说,我需要在另一个字段解析器中访问 parent.subscriptions(事件类型)。有点像 "force call" 订阅解析器。
这可能吗?如何实现?
谢谢! :)
您通常不应从另一个解析器调用一个解析器。如果您有两个或多个解析器通用的代码,您可以将该代码提取到它自己的函数中(可能还有一个单独的模块),然后从两个解析器中调用它。
因此您的代码可能如下所示:
subscriptions: {
type: new GraphQLList(EventType),
async resolve(parent, args) {
return getSubscriptionsByIds(parent._subscriptionIds)
},
},
anotherField: {
type: new AnotherType,
async resolve(parent, args) {
const subscriptions = await getSubscriptionsByIds(parent._subscriptionIds)
// do something else with the subscriptions here
},
},
但是,这将导致对您的数据库进行额外的调用,除非您已经在使用 DataLoader 来进行这样的批处理调用。更好的解决方案是将订阅获取逻辑上移一个级别(即,无论您在何处获取用户列表)。您可以使用 populate
或 $lookup
预先加载订阅,然后它们将通过每个用户字段解析器中的 parent
参数可用。
我有订阅活动的用户:
const EventType = new GraphQLObjectType({
name:'Event',
fields:() => ({
id: {type:GraphQLID}
})
});
const UserType = new GraphQLObjectType({
name:'User',
fields:() => ({
id: {type:GraphQLString},
_subscriptionIds: { type: new GraphQLList(GraphQLID) },
subscriptions: {
type: new GraphQLList(EventType),
async resolve(parent, args) {
return Event.find( {_id: { $in: parent._subscriptionIds}})
}
}
anotherField: {
type: new AnotherType,
async resolve(parent, args) {
console.log(parent.subscriptions) // parent.subscriptions is undefined, I need to resolve it.
}
})
});
长话短说,我需要在另一个字段解析器中访问 parent.subscriptions(事件类型)。有点像 "force call" 订阅解析器。
这可能吗?如何实现?
谢谢! :)
您通常不应从另一个解析器调用一个解析器。如果您有两个或多个解析器通用的代码,您可以将该代码提取到它自己的函数中(可能还有一个单独的模块),然后从两个解析器中调用它。
因此您的代码可能如下所示:
subscriptions: {
type: new GraphQLList(EventType),
async resolve(parent, args) {
return getSubscriptionsByIds(parent._subscriptionIds)
},
},
anotherField: {
type: new AnotherType,
async resolve(parent, args) {
const subscriptions = await getSubscriptionsByIds(parent._subscriptionIds)
// do something else with the subscriptions here
},
},
但是,这将导致对您的数据库进行额外的调用,除非您已经在使用 DataLoader 来进行这样的批处理调用。更好的解决方案是将订阅获取逻辑上移一个级别(即,无论您在何处获取用户列表)。您可以使用 populate
或 $lookup
预先加载订阅,然后它们将通过每个用户字段解析器中的 parent
参数可用。