【问题标题】:How does Relay / GraphQL 'resolve' works?Relay / GraphQL 'resolve' 是如何工作的?
【发布时间】:2015-11-20 12:09:39
【问题描述】:

我正在尝试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的一个例子(我用的是猫鼬):

articleSchema.methods.getAuthor = function(id){
  let article = this.model('Article').findOne({_id: id})
  return article.author
}

【问题讨论】:

    标签: javascript reactjs graphql relayjs graphql-js


    【解决方案1】:

    如果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);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-12
      • 2016-02-10
      • 1970-01-01
      • 2016-07-26
      • 2016-06-02
      • 2020-02-08
      • 2018-02-12
      • 2016-07-21
      • 2020-02-14
      相关资源
      最近更新 更多