本文介绍了带有表的GraphQL查询使用Node.js进行联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 GraphQL ,所以我建立了一个小项目.假设我有2个模型,分别是 User Comment .

I am learning GraphQL so I built a little project. Let's say I have 2 models, User and Comment.

const Comment = Model.define('Comment', {
  content: {
    type: DataType.TEXT,
    allowNull: false,
    validate: {
      notEmpty: true,
    },
  },
});

const User = Model.define('User', {
  name: {
    type: DataType.STRING,
    allowNull: false,
    validate: {
      notEmpty: true,
    },
  },
  phone: DataType.STRING,
  picture: DataType.STRING,
});

关系是一对多,其中用户可以有很多注释.
我建立了这样的架构:

The relations are one-to-many, where a user can have many comments.
I have built the schema like this:

const UserType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
    id: {
      type: GraphQLString
    },
    name: {
      type: GraphQLString
    },
    phone: {
      type: GraphQLString
    },
    comments: {
      type: new GraphQLList(CommentType),
      resolve: user => user.getComments()
    }
  })
});

查询:

const user = {
  type: UserType,
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLString)
    }
  },
  resolve(_, {id}) => User.findById(id)
};

执行用户查询和他的评论是通过1个请求完成的,就像这样:

Executing the query for a user and his comments is done with 1 request, like so:

{
  User(id:"1"){
    Comments{
      content
    }
  }
}

据我了解,客户端将使用1个查询获得结果,这是使用 GraphQL 的好处.但是服务器将执行2个查询,一个查询给用户,另一个查询给他的注释.

As I understand, the client will get the results using 1 query, this is the benefit using GraphQL. But the server will execute 2 queries, one for the user and another one for his comments.

我的问题是,构建 GraphQL 架构和类型以及组合表之间的联接以使服务器也可以通过1个请求执行查询的最佳实践是什么?

My question is, what are the best practices for building the GraphQL schema and types and combining join between tables, so that the server could also execute the query with 1 request?

推荐答案

您所引用的概念称为批处理.有几个提供此功能的库.例如:

The concept you are refering to is called batching. There are several libraries out there that offer this. For example:

  • 数据加载器:由Facebook维护的通用实用程序,可在各种后端和通过批处理和缓存减少对这些后端的请求"

  • Dataloader: generic utility maintained by Facebook that provides "a consistent API over various backends and reduce requests to those backends via batching and caching"

join-monster :针对GraphQL-to-SQL的查询执行层批量数据提取."

join-monster: "A GraphQL-to-SQL query execution layer for batch data fetching."

这篇关于带有表的GraphQL查询使用Node.js进行联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:33