简体   繁体   English

Relay / GraphQL'如何解决'有效吗?

[英]How does Relay / GraphQL 'resolve' works?

I am trying out Relay and GraphQL . 我正在尝试RelayGraphQL When I am doing the schema I am doing this: 当我在做模式时,我这样做:

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],
})

So, when I ask for an article like this: 所以,当我要求这样的文章时:

{
  article(id: 1) {
    id,
    title,
    author
  }
}

Will it do 3 queries to the database? 它会对数据库进行3次查询吗? I mean, each field has a resolve method ( getTitle , getAuthor , etc.) which does a request to the database. 我的意思是,每个字段都有一个解析方法( getTitlegetAuthor等),它向数据库发出请求。 Am I doing this wrong? 我做错了吗?

This is an example of getAuthor (I use mongoose): 这是getAuthor一个例子(我使用mongoose):

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

If the resolve method is passed the article , can't you just access the property? 如果通过了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],
})

Since Schema.methods in Mongoose defines methods on the model , it wouldn't take an ID for the article (because you call it on an article instance). 由于Mongoose中的Schema.methods定义了模型上的方法,因此它不会为文章提供ID(因为您在文章实例上调用它)。 So, if you wanted to keep the method, you would just do: 所以,如果你想保留这个方法,你会这样做:

articleSchema.methods.getAuthor = function() {
  return article.author;
}

If it was something you need to look up eg in another collection, then you'd need to do a separate query (assuming you're not using refs): 如果你需要在另一个集合中查找它, 那么你需要做一个单独的查询(假设你没有使用refs):

articleSchema.methods.getAuthor = function(callback) {
  return this.model('Author').find({ _id: this.author_id }, cb);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM