Relay / GraphQL 'resolve'的工作原理
How does Relay / GraphQL 'resolve' works?
我正在尝试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);
}
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- jQuery UI自动完成突然停止工作
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JavaScript打印功能使日历停止工作
- Javascript.getHours()工作不正常
- 为什么这在IE中的工作方式与在Firefox中不同
- 视频HTML没有'无法在Internet Explorer 11上工作
- 扩展移相器按钮类不工作
- Firebase迁移-简单的Firebase.set没有'不再工作了——旧的还是新的
- 谷歌地图不是以HTML显示,而是在JS Fiddle上工作
- 正在尝试使用if和else添加类,但无法正常工作
- Jquery FadeIn FadeOut 只工作一次
- Foreach无法在Typescript中工作
- 另一个ajax调用中的Jquery ajax调用在for循环中没有按预期工作
- 为什么不是't窗口.恢复正常工作吗?(javascript/jquery)
- JS可以在Chrome中工作,但不能在Firefox中工作
- 当一个promise的resolve回调返回另一个promise时,它是如何工作的
- 没有resolve选项,Angularjs ui bootstrap modal不能工作
- Relay / GraphQL 'resolve'的工作原理