Magento, Magento 2

How to Set Limit of Query Complexity and Depth of GraphQL in Magento 2

How to Set Limit of Query Complexity and Depth of GraphQL in Magento 2

In this tutorial, Today I will explain to how to set limit of query complexity and depth of graphql in Magento 2. Magento 2.3 has added GraphQL functionality. However, It will allow some queries that is not useful in your custom frontend query execution. To avoid that type execution, we can set limit of query complexity and depth level of GraphQL query in Magento 2. Let’s see how can we set that :

You may also like this :

1) Let’s assume that you have created simple module. Now, you need to create di.xml file at below path app/code/RH/Helloworld/etc/ and paste the below code :

<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!-- Increased Query depth from 20 to 25 -->
    <!-- Increased Query complexity from 300 to 450 -->
    <type name="Magento\Framework\GraphQl\Query\QueryComplexityLimiter">
        <arguments>
            <argument name="queryDepth" xsi:type="number">25</argument>
            <argument name="queryComplexity" xsi:type="number">450</argument>
        </arguments>
    </type>
</config>

2) Now, You just need to clean cache and execute graphql query to check result.

If depth and complexity will higher than set limit. Then, it will return error like this :

{
  "errors": [
    {
      "message": "Max query depth should be 25 but got 30.",
      "extensions": {
        "category": "graphql"
      }
    }
  ]
}

That’s it !!!

I hope this blog is easy to understand about how to set limit of query complexity and depth of graphql in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged , ,