简体   繁体   English

Api-Platform graphql - 在一个突变中创建多个项目

[英]Api-Platform graphql - create multiple items in one mutation

I have an User entity that can add his/hers contacts from Google using GooglePeopleApi.我有一个用户实体,可以使用 GooglePeopleApi 从 Google 添加他/她的联系人。

The API provides an array of contacts to the front-end as it is (Nextjs). API 按原样向前端提供一组联系人 (Nextjs)。 The question is how to insert all those contacts in one single mutation.问题是如何将所有这些联系人插入一个单一的突变中。

I could, of course, have the front-end loop through the array and post the contacts one by one, but that is a bit silly.当然,我可以让前端循环遍历数组并一个接一个地发布联系人,但这有点傻。

It should be possible to create a type array with the Contact input and then, with that, set up a customArgsMutation .应该可以使用 Contact 输入创建一个类型数组,然后设置一个customArgsMutation ( I've seen some examples of that from Hasura ). (我从 Hasura 那里看到了一些这样的例子)。

Entity wise, it looks like this for now ( only relevant code ):实体方面,现在看起来像这样(只有相关代码):

User.php用户.php

 ....
/**
 * @ORM\OneToMany(targetEntity="App\Entity\Contact", mappedBy="user")
 * @Groups({"put-contacts", "get-admin", "get-owner"})
 */
private $contacts;

Contact.php联系人:php

/**
* @ApiResource(
*      attributes={"pagination_enabled"=false},
*      graphql={
*          "item_query"={
*              "normalization_context"={"groups"={"get-admin", "get-owner"}},
*          },
*          "collection_query"={
*              "normalization_context"={"groups"={"get-admin", "get-owner"}},
*          },
*          "delete"={"security"="is_granted('IS_AUTHENTICATED_FULLY') and object.getUser() == user"},
*          "create"={
*              "security"="is_granted('IS_AUTHENTICATED_FULLY')",
*              "denormalization_context"={"groups"={"post", "put"}},
*              "normalization_context"={"groups"={"get-owner", "get-admin"}},
*          },
*      }
* )
* @ORM\Entity(repositoryClass="App\Repository\ContactRepository")
*/
class Contact
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="contacts")
 * @Groups({"post", "get-admin", "get-owner"})
 */
private $user;

/**
 * @ORM\Column(type="string", length=180)
 * @Groups({"post", "put", "get-admin", "get-owner"})
 */
private $email;

/**
 * @ORM\Column(type="string", length=180, nullable=true)
 * @Groups({"post", "put", "get-admin", "get-owner"})
 */
private $familyName;

/**
 * @ORM\Column(type="string", length=180, nullable=true)
 * @Groups({"post", "put", "get-admin", "get-owner"})
 */
private $givenName;

/**
 * @ORM\Column(type="string", length=180, nullable=true)
 * @Groups({"post", "put", "get-admin", "get-owner"})
 */
private $displayName;

From graphiql , the createContact input looks like this:graphiql中, createContact输入如下所示:

 user: String
 email: String!
 familyName: String
 givenName: String
 displayName: String
 clientMutationId: String

You have a couple of options here, depending on the amount of concurrency you want:您在这里有几个选项,具体取决于您想要的并发量:

1. These should be performed in Serial 1. 这些应该在串行执行

The client can make a single HTTP request with multiple mutations as aliases:客户端可以使用多个突变作为别名发出单个 HTTP 请求:

mutation CreateUsers {
  user1: createUser({ //userInput1 }) { ...userFields }
  user2: createUser({ //userInput2 }) { ...userFields }
  user3: createUser({ //userInput3 }) { ...userFields }
}

fragment userFields on CreateUserPayload {
  firstName
  // etc
}

The response will look like this:响应将如下所示:

{
  "data": {
    "user1": {...},
    "user2": {...},
    "user3": {...},
  }
}

Pros :优点

  • If any single mutation fails, just that one will error out without special handling如果任何一个突变失败,只要没有特殊处理就会出错
  • Order is maintained.秩序得以维持。 Because the API consumer is specifically labelling the mutations, they know which one has which results.因为 API 使用者专门标记了突变,所以他们知道哪个有哪个结果。

Cons :缺点

  • By design, multiple mutations run in Serial, where the first must complete fully before the next one is started.按照设计,多个变更在 Serial 中运行,其中第一个必须在下一个开始之前完全完成。 Because of this it's going to be a bit slower.正因为如此,它会慢一点。
  • The client has to add the fields themselves or use a fragment for each mutation (what I showed above)客户端必须自己添加字段或为每个突变使用一个片段(我上面展示的)

2. These should be performed in Parallel 2. 这些应该并行执行

It is a common practice (as common as it can be, I guess) to create a "bulk mutation" that allows you to create multiple users.创建一个允许您创建多个用户的“批量突变”是一种常见的做法(我猜这很常见)。

mutation CreateUsers {
  createUsers([
    { //userInput1 },
    { //userInput2 },
    { //userInput3 }
  ]) {
    firstName
    // etc
  }
}

Pros :优点

  • Runs in parallel, so it's faster并行运行,所以速度更快
  • The client doesn't have to do string interpolation to build the query.客户端不必进行字符串插值来构建查询。 They just need the array of objects to pass in.他们只需要传入的对象数组。

Cons :缺点

  • You have to build the logic yourself to be able to return nulls vs errors on your own.您必须自己构建逻辑才能自行返回空值与错误。
  • You have to build the logic to maintain order你必须建立逻辑来维持秩序
  • The client has to build logic to find their results in the response array if they care about order.如果客户端关心顺序,则必须构建逻辑以在响应数组中查找结果。

This is how I did it:我就是这样做的:

Create a custom type:创建自定义类型:

class CustomType extends InputObjectType implements TypeInterface
{
    public function __construct()
    {
        $config = [
            'name' => 'CustomType',
            'fields' => [
                'id_1' => Type::nonNull(Type::id()),
                'id_2' => Type::nonNull(Type::id()),
                'value' => Type::string(),
            ],
        ];
        parent::__construct($config);
    }

    public function getName(): string
    {
        return 'CustomType';
    }
}

Register CustomType in src/config/services.yaml在 src/config/services.yaml 中注册 CustomType

(...)
App\Type\Definition\CustomType:
    tags:
        - { name: api_platform.graphql.type }

Add custom mutation to entity, using CustomType argument as array:将自定义突变添加到实体,使用 CustomType 参数作为数组:

/**
* @ApiResource(
* (...)
*     graphql={
*     "customMutation"={
*         "args"={
*             (...)
*             "customArgumentName"={"type"=[CustomType!]"}
*         }
*     }
*)

Then the new customMutation can be called with an array of arguments like this:然后可以使用 arguments 数组调用新的 customMutation,如下所示:

mutation myMutation($input: customMutationEntitynameInput!) {
    customMutationEntityname(input: $input) {
        otherEntity {
            id
        }
    }
}

And graphql variables:和 graphql 个变量:

{
    "input": {
        "customArgumentName": [
            {
                "id_1": 3,
                "id_2": 4
            },{
                "id_1": 4,
                "id_2": 4
            }
        ]
    }
}

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

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