Получить атрибут Customer в Magento2 с помощью GraphQL

#graphql #magento2

#graphql #magento2

Вопрос:

Я создал новые атрибуты для customer, но я хочу вставить их в структуру в graphql. Где есть массив с именем Garage с новыми атрибутами. Он уже нормально отображается в структуре, когда я использую статические данные, но теперь мне нужно сделать его динамическим через базу данных в соответствии с идентификатором клиента. Увидев модель самого клиента, я увидел, что выполняется команда для приведения, но я хотел бы привести элемент за элементом и поместить его в массив.

CustomerGarage.php

     <?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace EnterpriseGraphQLModelResolver;

use MagentoCustomerGraphQlModelCustomerGetCustomer;
use MagentoFrameworkGraphQlExceptionGraphQlAuthorizationException;
use MagentoFrameworkGraphQlSchemaTypeResolveInfo;
use MagentoCustomerGraphQlModelCustomerExtractCustomerData;
use MagentoFrameworkGraphQlConfigElementField;
use MagentoFrameworkGraphQlQueryResolverInterface;
use MagentoGraphQlModelQueryContextInterface;

/**
 * Customers field resolver, used for GraphQL request processing.
 */
class CustomerGarage implements ResolverInterface
{
    /**
     * @var GetCustomer
     */
    private $getCustomer;

    /**
     * @var ExtractCustomerData
     */
    private $extractCustomerData;

    /**
     * @param GetCustomer $getCustomer
     * @param ExtractCustomerData $extractCustomerData
     */
    public function __construct(
        GetCustomer $getCustomer,
        ExtractCustomerData $extractCustomerData
    ) {
        $this->getCustomer = $getCustomer;
        $this->extractCustomerData = $extractCustomerData;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        /** @var ContextInterface $context */
        if (false === $context->getExtensionAttributes()->getIsCustomer()) {
            throw new GraphQlAuthorizationException(__('The current customer isn't authorized.'));
        }

        $customer = $this->getCustomer->execute($context);
        
        $model[] = array(
            "make" => "Teste",
            "model" => $this->extractCustomerData->execute($customer),
            "specification" => "1.0",
            "year" => 2020,
            "isDefault" => "Teste"
        );
        
        return $model;
    }
}
  

Schema.graphql

 type Customer {
    garage: [CustomerGarage] @doc(description: "An array containing the customer's shipping and billing addresses") @resolver(class: "Enterprise\GraphQL\Model\Resolver\CustomerGarage")
}

type CustomerGarage {
    make: String @doc(description: "The customer's ZIP or postal code")
    model: String @doc(description: "The customer's ZIP or postal code")
    specification: String @doc(description: "The customer's ZIP or postal code")
    year: Int
    isDefault: String @doc(description: "The customer's ZIP or postal code")
}
type Cart {
    vehicle: String
    isPickup: Boolean
    scheduledDate: String
}
  

Требуется GraphQL

 {
  customer {
    firstname
    lastname
    garage{
      make
      model
    }
  }
  

ResponseGraphQL

 {
  "errors": [
    {
      "message": "Internal server error",
      "extensions": {
        "category": "internal"
      },
      "locations": [
        {
          "line": 5,
          "column": 5
        }
      ],
      "path": [
        "customer",
        "garage"
      ]
    }
  ],
  "data": {
    "customer": {
      "firstname": "Carlo",
      "lastname": "Sanchez",
      "garage": null
    }
  }
}
    }
  

Комментарии:

1. вы «моделируете» определение атрибута graphql, указывающее, что оно имеет строковое значение, но MagentoCustomerGraphQlModelCustomerExtractCustomerData::execute возвращает массив, вы добавляете значение (массив) непосредственно в качестве значения модели, кажется, это немного не так

Ответ №1:

параметр resolver $value уже должен содержать все данные клиента, загруженные в массив, вы можете проверить, есть ли у вас там нужные данные. И если вам нужен экземпляр модели данных клиента, вы можете получить его из $value['model'] .

Это связано с тем, что значение параметра $value равно тому, что возвращает родительский преобразователь, в данном случае оно MagentoCustomerGraphQlModelResolverCustomer::resolve определено здесь vendor/magento/module-customer-graph-ql/etc/schema.graphqls