Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5490

Adding Identity Class for Graph QL Cacheable Queries in Magento 2

$
0
0

Requirements for implementing Cacheable queries.

  • An Identity class that must return unique identifiers for cache tags that can be invalidated when an entity changes.
  • The class must implement Magento\Framework\GraphQl\Query\Resolver\IdentityInterface. Below is an example of class Implementing the Identity interface.
<?php
declare(strict_types=1);

namespace PathToModule\Model\Resolver\MyModule;

use Magento\Framework\GraphQl\Query\Resolver\IdentityInterface;

/**
 * Get identities from resolved data
 */
class MyIdentity implements IdentityInterface
{
    private $cacheTag = \PathToModule\Model\MyEntity::CACHE_TAG;

    /**
     * Get identity tags from resolved data
     *
     * @param array $resolvedData
     * @return string[]
     */
    public function getIdentities(array $resolvedData): array
    {
        $ids = [];
        $items = $resolvedData['items'] ?? [];
        foreach ($items as $item) {
            $ids[] = sprintf('%s_%s', $this->cacheTag, $item['entity_id']);
        }
        if (!empty($ids)) {
            $ids[] = $this->cacheTag;
        }
        return $ids;
    }
}
  • The getIdentities method must return an unique cache tag for each entity contained in the $resolvedData array.
  • Use the @cache directive in your schema.graphqls file to specify the location of Identity class.
  • Below is an example.
      categoryList(
    filters: CategoryFilterInput @doc(description: "Identifies which Category filter inputs to search for and return.")
    ): [CategoryTree] @doc(description: "Returns an array of categories based on the specified filters.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\CategoryList") @cache(cacheIdentity: "Magento\\CatalogGraphQl\\Model\\Resolver\\Category\\CategoriesIdentity")
}


Viewing all articles
Browse latest Browse all 5490

Trending Articles