javascript - Relay/GraphQL 'resolve' 是如何工作的?

标签 javascript reactjs graphql relayjs graphql-js

我正在尝试 RelayGraphQL .当我在做模式时,我是这样做的:

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 次查询吗?我的意思是,每个字段都有一个向数据库发出请求的解析方法(getTitlegetAuthor 等)。我做错了吗?

这是一个 getAuthor 的例子(我用的是 mongoose):

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 - Relay/GraphQL 'resolve' 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226857/

相关文章:

javascript - 如何使用 Javascript、表值复选框、文本框、单选框、选择选项在表中添加行?

javascript - JS : Changing an input's text(value) on file input file select

javascript - 为什么我的路线没有加载我的 React 组件?

python - 如何使用 django_graphene 解析 django 模型的自定义字段?

schema - 为分析平台设计 GraphQL 模式

node.js - 使用 graphQlObjectType 的 graphQl 模式

javascript - 内部 (if) 2 个参数在 Firefox 上不起作用

javascript - HTML 多选提交在已添加值时中断

reactjs - 将组件和 Prop 作为参数传递

javascript - 在 reactjs 中使用渲染方法之外的函数