Back to Top

Create Cacheable GraphQl Query Magento 2

Updated 23 April 2024

When implementing a cacheable graphql query akin to those for product, category, and CMS data in Magento 2, it’s essential to develop an Identity class(Magento\Framework\GraphQl\Query\Resolver\IdentityInterface) for the module.

This class is responsible for providing unique identifiers for cache tags, enabling the system to invalidate cache entries appropriately when relevant entities undergo changes.

Ensure to position this Identity class within your module’s Model/Resolver directory for streamlined integration with Magento’s GraphQL caching mechanism.

  • 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 should provide a unique cache tag for each entity present in the $resolvedData array.
  • Incorporate the @cache directive within your module’s GraphQL schema file (graphqls) to indicate the location of your Identity class. Ensure that your module’s graphqls file references your Identity class appropriately, as demonstrated below:
      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")
}

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home