PHP / Magento Dev Blog

  • Publikacje
  • O autorze
  • Kontakt

GraphQL custom resolver w Magento 2 – schemat, autoryzacja, testy

by Henryk Tews / środa, 29 lipca 2026 / Opublikowano w Magento / Adobe Commerce

GraphQL w Magento 2 to nie tylko API do odczytu – możesz dodać własne typy, queries i mutations. Custom resolver to klasa PHP która odpowiada za pobranie danych dla danego pola lub query. Pokażę kompletną implementację: schemat GraphQL, resolver z autoryzacją, obsługę błędów i testy integracyjne. Na przykładzie query pobierającego historię zamówień klienta z filtrami.

Schemat GraphQL – schema.graphqls

// app/code/Vendor/OrderHistory/etc/schema.graphqls

type Query {
    customerOrderHistory(
        filter: OrderHistoryFilterInput
        pageSize: Int = 20
        currentPage: Int = 1
    ): OrderHistoryOutput @resolver(class: "Vendor\\OrderHistory\\Model\\Resolver\\OrderHistory") @doc(description: "Get customer order history")
}

input OrderHistoryFilterInput {
    status: FilterEqualTypeInput
    date_from: FilterStringTypeInput
    date_to: FilterStringTypeInput
    min_amount: FilterRangeTypeInput
}

type OrderHistoryOutput {
    items: [CustomerOrderItem]
    total_count: Int
    page_info: SearchResultPageInfo
}

type CustomerOrderItem {
    id: ID!
    increment_id: String!
    status: String!
    created_at: String!
    grand_total: Float!
    currency_code: String!
    items_count: Int!
    shipping_address: OrderAddress
}

type OrderAddress {
    firstname: String
    lastname: String
    street: [String]
    city: String
    postcode: String
    country_code: String
}

Resolver – główna klasa

<?php

declare(strict_types=1);

namespace Vendor\OrderHistory\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\GraphQl\Model\Query\ContextInterface;

class OrderHistory implements ResolverInterface
{
    public function __construct(
        private \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        private \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
        private \Magento\Framework\Api\FilterBuilder $filterBuilder,
        private \Magento\Framework\Api\SortOrderBuilder $sortOrderBuilder,
    ) {}

    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ): array {
        /** @var ContextInterface $context */

        // Autoryzacja - tylko zalogowany klient
        if (!$context->getExtensionAttributes()->getIsCustomer()) {
            throw new GraphQlAuthorizationException(
                __('Customer must be logged in to view order history')
            );
        }

        $customerId = $context->getUserId();
        $pageSize   = $args['pageSize'] ?? 20;
        $currentPage= $args['currentPage'] ?? 1;

        // Walidacja paginacji
        if ($pageSize > 100) {
            throw new GraphQlInputException(__('pageSize cannot exceed 100'));
        }

        // Buduj kryteria wyszukiwania
        $this->searchCriteriaBuilder->addFilter('customer_id', $customerId);
        $this->applyFilters($args['filter'] ?? []);

        // Sortowanie - najnowsze pierwsze
        $sortOrder = $this->sortOrderBuilder
            ->setField('created_at')
            ->setDescendingDirection()
            ->create();
        $this->searchCriteriaBuilder->setSortOrders([$sortOrder]);

        // Paginacja
        $this->searchCriteriaBuilder
            ->setPageSize($pageSize)
            ->setCurrentPage($currentPage);

        $searchCriteria = $this->searchCriteriaBuilder->create();
        $result         = $this->orderRepository->getList($searchCriteria);

        return [
            'total_count' => $result->getTotalCount(),
            'page_info'   => [
                'page_size'    => $pageSize,
                'current_page' => $currentPage,
                'total_pages'  => (int)ceil($result->getTotalCount() / $pageSize),
            ],
            'items' => $this->formatOrders($result->getItems()),
        ];
    }

    private function applyFilters(array $filter): void
    {
        if (!empty($filter['status']['eq'])) {
            $this->searchCriteriaBuilder->addFilter('status', $filter['status']['eq']);
        }

        if (!empty($filter['date_from']['match'])) {
            $this->searchCriteriaBuilder->addFilter(
                'created_at', $filter['date_from']['match'], 'gteq'
            );
        }

        if (!empty($filter['date_to']['match'])) {
            $this->searchCriteriaBuilder->addFilter(
                'created_at', $filter['date_to']['match'], 'lteq'
            );
        }

        if (!empty($filter['min_amount']['from'])) {
            $this->searchCriteriaBuilder->addFilter(
                'grand_total', $filter['min_amount']['from'], 'gteq'
            );
        }
    }

    private function formatOrders(array $orders): array
    {
        $result = [];
        foreach ($orders as $order) {
            $shippingAddress = $order->getShippingAddress();
            $result[] = [
                'id'           => base64_encode('Order/' . $order->getId()),
                'increment_id' => $order->getIncrementId(),
                'status'       => $order->getStatus(),
                'created_at'   => $order->getCreatedAt(),
                'grand_total'  => (float)$order->getGrandTotal(),
                'currency_code'=> $order->getOrderCurrencyCode(),
                'items_count'  => (int)$order->getTotalItemCount(),
                'shipping_address' => $shippingAddress ? [
                    'firstname'   => $shippingAddress->getFirstname(),
                    'lastname'    => $shippingAddress->getLastname(),
                    'street'      => $shippingAddress->getStreet(),
                    'city'        => $shippingAddress->getCity(),
                    'postcode'    => $shippingAddress->getPostcode(),
                    'country_code'=> $shippingAddress->getCountryId(),
                ] : null,
            ];
        }
        return $result;
    }
}

Przykładowe query

query GetOrderHistory {
    customerOrderHistory(
        filter: {
            status: { eq: "complete" }
            date_from: { match: "2026-01-01" }
            min_amount: { from: "100" }
        }
        pageSize: 10
        currentPage: 1
    ) {
        total_count
        page_info {
            current_page
            total_pages
        }
        items {
            increment_id
            status
            created_at
            grand_total
            currency_code
            shipping_address {
                firstname
                lastname
                city
            }
        }
    }
}

Test integracyjny resolwera

<?php

declare(strict_types=1);

namespace Vendor\OrderHistory\Test\Integration\Model\Resolver;

use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQlAbstract;

class OrderHistoryTest extends GraphQlAbstract
{
    private const QUERY = <<<GRAPHQL
    query {
        customerOrderHistory(pageSize: 5) {
            total_count
            items {
                increment_id
                status
                grand_total
            }
        }
    }
    GRAPHQL;

    public function testGuestCannotAccessOrderHistory(): void
    {
        $this->expectException(\Magento\Framework\Exception\LocalizedException::class);
        $this->graphQlQuery(self::QUERY);
    }

    /**
     * @magentoDataFixture Vendor_OrderHistory::Test/Integration/_files/customer_with_orders.php
     */
    public function testCustomerCanGetOrderHistory(): void
    {
        $headers  = $this->getCustomerAuthHeaders('customer@example.com', 'password123');
        $response = $this->graphQlQuery(self::QUERY, [], '', $headers);

        $this->assertArrayHasKey('customerOrderHistory', $response);
        $this->assertGreaterThan(0, $response['customerOrderHistory']['total_count']);
        $this->assertNotEmpty($response['customerOrderHistory']['items']);

        $firstOrder = $response['customerOrderHistory']['items'][0];
        $this->assertArrayHasKey('increment_id', $firstOrder);
        $this->assertArrayHasKey('grand_total', $firstOrder);
    }

    private function getCustomerAuthHeaders(string $email, string $password): array
    {
        $mutation = <<<MUTATION
        mutation {
            generateCustomerToken(email: "{$email}", password: "{$password}") {
                token
            }
        }
        MUTATION;

        $response = $this->graphQlMutation($mutation);
        $token    = $response['generateCustomerToken']['token'];

        return ['Authorization' => 'Bearer ' . $token];
    }
}

Podsumowanie

Custom resolver w Magento 2 GraphQL to implementacja ResolverInterface z metodą resolve(). Autoryzacja przez $context->getExtensionAttributes()->getIsCustomer(). Błędy przez GraphQlAuthorizationException lub GraphQlInputException – trafiają do pola errors w odpowiedzi. Schemat definiujesz w schema.graphqls – Magento automatycznie łączy go z resolverem przez dyrektywę @resolver. Testy integracyjne przez GraphQlAbstract pozwalają testować pełny stack bez mockowania.

About Henryk Tews

Co możesz przeczytać następne

OpenSearch 3.x vector search – embeddingi przez Ollama, k-NN, hybrid search
Magento 2 utrata koszyka – Redis session i eviction policy
Magento 2 Varnish cache nie działa – hit rate 0% i błędna konfiguracja VCL
  • Publikacje
  • O autorze
  • Kontakt

© 2026 Created by

GÓRA
Zarządzaj zgodą
Aby zapewnić jak najlepsze wrażenia, korzystamy z technologii, takich jak pliki cookie, do przechowywania i/lub uzyskiwania dostępu do informacji o urządzeniu. Zgoda na te technologie pozwoli nam przetwarzać dane, takie jak zachowanie podczas przeglądania lub unikalne identyfikatory na tej stronie. Brak wyrażenia zgody lub wycofanie zgody może niekorzystnie wpłynąć na niektóre cechy i funkcje.
Funkcjonalne Zawsze aktywne
Przechowywanie lub dostęp do danych technicznych jest ściśle konieczny do uzasadnionego celu umożliwienia korzystania z konkretnej usługi wyraźnie żądanej przez subskrybenta lub użytkownika, lub wyłącznie w celu przeprowadzenia transmisji komunikatu przez sieć łączności elektronicznej.
Preferencje
Przechowywanie lub dostęp techniczny jest niezbędny do uzasadnionego celu przechowywania preferencji, o które nie prosi subskrybent lub użytkownik.
Statystyka
Przechowywanie techniczne lub dostęp, który jest używany wyłącznie do celów statystycznych. Przechowywanie techniczne lub dostęp, który jest używany wyłącznie do anonimowych celów statystycznych. Bez wezwania do sądu, dobrowolnego podporządkowania się dostawcy usług internetowych lub dodatkowych zapisów od strony trzeciej, informacje przechowywane lub pobierane wyłącznie w tym celu zwykle nie mogą być wykorzystywane do identyfikacji użytkownika.
Marketing
Przechowywanie lub dostęp techniczny jest wymagany do tworzenia profili użytkowników w celu wysyłania reklam lub śledzenia użytkownika na stronie internetowej lub na kilku stronach internetowych w podobnych celach marketingowych.
  • Zarządzaj opcjami
  • Zarządzaj serwisami
  • Zarządzaj {vendor_count} dostawcami
  • Przeczytaj więcej o tych celach
Zobacz preferencje
  • {title}
  • {title}
  • {title}