首页 > 解决方案 > 为什么我创建的动态序列化组不允许指定属性的突变?

问题描述

我已经通过 Context Builder 为管理员用户实现了一个动态序列化组(添加 admin:write)。并已将此组分配给我只想由管理员通过 GraphQL 更新的属性。

我此时的实现直接取自https://api-platform.com/docs/core/graphql/#sharing-the-serialization-context-dynamically

但是当试图改变这个属性时,我收到一个错误,上面写着Field "roles" is not defined by type updateUserInput.

这对我来说很有意义,因为架构不包含此属性,因为它不在典型write组中。但是,文档表明这应该是可行的。如果是这种情况,我做错了什么?

相关代码:

上下文构建器

<?php

namespace App\Serializer;

use ApiPlatform\Core\GraphQl\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * Context Builder: Experimental implementation used for constructing what resources are returned.
 */
final class AdminGroupsContextBuilder implements SerializerContextBuilderInterface {
  private $decorated;
  private $authorizationChecker;

  /**
   *
   */
  public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker) {
    $this->decorated = $decorated;
    $this->authorizationChecker = $authorizationChecker;
  }

  /**
   *
   */
  public function create(?string $resourceClass, string $operationName, array $resolverContext, bool $normalization): array {
    $context = $this->decorated->create($resourceClass, $operationName, $resolverContext, $normalization);
    $resourceClass = $context['resource_class'] ?? NULL;

    if (isset($context['groups']) && $this->authorizationChecker->isGranted('ROLE_ADMIN') && FALSE === $normalization) {
      $context['groups'][] = 'admin:input';
    }

    return $context;
  }

}

用户实体类属性定义

  /**
   * @ORM\Column(type="json")
   * @Groups({"read", "admin:write"})
   */
  private $roles = [];

服务定义

    App\Serializer\AdminGroupsContextBuilder:
        decorates: 'api_platform.graphql.serializer.context_builder'
        arguments: [ '@App\Serializer\AdminGroupsContextBuilder.inner' ]
        autoconfigure: false

标签: serializationgraphqlapi-platform.com

解决方案


推荐阅读