简体   繁体   English

如何使用 GraphQL 突变减少请求数量?

[英]How to decrease request numbers with GraphQL mutations?

I want to decrease number of requests to graphql server.我想减少对graphql 服务器的请求数 I have objects in an array like我在数组中有对象

 [{name: "gokhan", age: 20}, ...];

I use graphql a mutation to add every item of an array.我使用 graphql 突变来添加数组的每个项目。

If The array has 50 items, I need to send 50 requests to add all data.如果数组有 50 个项目,我需要发送50 个请求来添加所有数据。 Is there any way to decrease the number of requests?有没有办法减少请求的数量?

There's two main options to solve this:有两个主要选项可以解决这个问题:

Option 1 (preferred): add a new mutation to your GraphQL schema that handles a GraphQLList of these input objects.选项 1(首选):向处理这些输入对象的GraphQLList的 GraphQL 模式添加新的GraphQLList How you'd do this would change depending on what GraphQL server you're using (in PostGraphile you'd use a custom mutation or schema extension );您如何执行此操作将取决于您使用的 GraphQL 服务器(在 PostGraphile 中,您将使用自定义突变模式扩展); but the Schema Definition Language might look like this:但架构定义语言可能如下所示:

input CreateManyPeopleInput {
  people: [CreatePersonInput!]!
}

type CreateManyPeoplePayload {
  createdPeople: [Person!]
}

extend type Mutation {
  createManyPeople(input: CreateManyPeopleInput): CreateManyPeoplePayload
}

Option 2: enable "query batching" .选项 2:启用“查询批处理” To use this, you will need both a server and a client that support GraphQL Query Batching.要使用它,您将需要支持 GraphQL 查询批处理的服务器和客户端。 Essentially it allows you to send multiple GraphQL queries in one request and get all the responses in one response.本质上,它允许您在一个请求中发送多个 GraphQL 查询,并在一个响应中获取所有响应。 This doesn't require any changes to your GraphQL schema, but it won't be as efficient and typical implementations only allow batching ~10 queries into one request so your 50 creates might still require 5 requests.这不需要对您的 GraphQL 架构进行任何更改,但它不会那么高效,并且典型的实现只允许将约 10 个查询批处理到一个请求中,因此您的 50 个创建可能仍需要 5 个请求。

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

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