Relay / GraphQL'resolve'是如何工作的?
我正在尝试Relay和GraphQL。 当我在做模式时,我正在这样做:
let articleQLO = new GraphQLObjectType({
name: 'Article',
description: 'An article',
fields: () => ({
_id: globalIdField('Article'),
title: {
type: GraphQLString,
description: 'The title of the article',
resolve: (article) => article.getTitle(),
},
author: {
type: userConnection,
description: 'The author of the article',
resolve: (article) => article.getAuthor(),
},
}),
interfaces: [nodeInterface],
})
所以,当我要求这样一篇文章时:
{
article(id: 1) {
id,
title,
author
}
}
它会对数据库执行3个查询吗? 我的意思是,每个字段都有一个解析方法(getTitle,getAuthor ...),它向数据库发出请求。 我做错了吗?
这是getAuthor(我使用猫鼬)的一个例子:
articleSchema.methods.getAuthor = function(id){
let article = this.model('Article').findOne({_id: id})
return article.author
}
如果resolve
方法通过article
,您不能只访问该属性?
let articleQLO = new GraphQLObjectType({
name: 'Article',
description: 'An article',
fields: () => ({
_id: globalIdField('Article'),
title: {
type: GraphQLString,
description: 'The title of the article',
resolve: (article) => article.title,
},
author: {
type: userConnection,
description: 'The author of the article',
resolve: (article) => article.author,
},
}),
interfaces: [nodeInterface],
})
由于Mongoose中的Schema.methods
在模型中定义了方法,因此它不会为文章带上一个ID(因为您在文章实例上调用它)。 所以,如果你想保留这个方法,你可以这样做:
articleSchema.methods.getAuthor = function() {
return article.author;
}
如果这是你需要查看的东西,例如在另一个集合中,那么你需要做一个单独的查询(假设你没有使用refs):
articleSchema.methods.getAuthor = function(callback) {
return this.model('Author').find({ _id: this.author_id }, cb);
}
链接地址: http://www.djcxy.com/p/87569.html