使用 Node.js 连接表的 GraphQL 查询 [英] GraphQL queries with tables join using Node.js

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

问题描述

我正在学习 GraphQL 所以我构建了一个小项目.假设我有 2 个模型,UserComment.

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:

  • Dataloader:由 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."

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆