0

I am creating my custom query in GraphQl and getting this error i searched alot but couldnot resolve my errors by the solutions given

My schema.graphq

type Query {
    getProductBySku(sku: String!): Product @resolver(class: "Vendor\\GraphQl\\Model\\Resolver\\GetProductBySku") @doc(description: "Get product details by SKU")
}

type Product {
    sku: String!
    name: String!
    description: String
    price: Float!
    image: String
}

Resolver File

<?php

namespace Vendor\GraphQl\Model\Resolver;

use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;

class GetProductBySku implements ResolverInterface
{
    /**
     * @var ProductRepository
     */
    private $productRepository;

    public function __construct(
        ProductRepository $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {
        $sku = $args['sku'];

        try {
            $product = $this->productRepository->get($sku);
            $productData = [
                'sku' => $product->getSku(),
                'name' => $product->getName(),
                'description' => $product->getDescription(),
                'price' => $product->getFinalPrice(),
                'image' => $this->getImageUrl($product),
            ];

            return $productData;
        } catch (\Exception $e) {
            return null; // Return null or handle the error as needed
        }
    }

    private function getImageUrl($product)
    {
        $image = $product->getMediaGalleryImages()->getFirstItem();
        return $image->getUrl();
    }
}
1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.