Skip to content

Magento2: Disable / Modify GraphQL Field Suggestion

In GraphQL, if we enter wrong field name in search, its will suggest the alternative fields in the response. It creates some security issues in production. So we plan to disable that feature. unfortunately adobe commerce not having the out of box feature.

Query:

{
  products(
        filter: { sku: { eq: "SKU"} }
  ) {
  items {
      new_items {
        name
        sk
      }
    }
  }
}

Response:

{
    "errors": [
        {
            "message": "Cannot query field "sk" on type "NewItems". Did you mean "sku"?",
            "locations": [
                {
                    "line": 8,
                    "column": 9
                }
            ]
        }
    ]
}

We found, this particular createFromException function in this class vendor/webonyx/graphql-php/src/Error/FormattedError.php responsible for modifying the response.

But, Its a static or class method, so we can’t able to override via preference or plugins in magento 2.

So we try to overload that function using __callStatic magic method in php. Its unable to call this my custom function to modify the response.

pls suggest what was missing below and suggest me any alternative solution. Thanks in advance

What we did:

VendorModuleetcdi.xmi:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="GraphQLErrorFormattedError" type="VendorModuleErrorCustomFormattedError" />
</config>

VendorModuleErrorCustomFormattedError.php:

<?php

namespace VendorModuleError;

use GraphQLErrorError;
use GraphQLErrorFormattedError as BaseFormattedError;
use PsrLogLoggerInterface;

class CustomFormattedError extends BaseFormattedError
{

    public static function __callStatic($name, $arguments)
    {
        if ($name === 'createFromException') {
       
            $formattedError = parent::createFromException(...$arguments);

            if (isset($formattedError['message']) && str_contains($formattedError['message'], 'Did you mean')) {
                $formattedError['message'] = 'Invalid query field.';
            }

            return $formattedError;
        }

        return parent::__callStatic($name, $arguments);
    }
}

Reference:

https://stackoverflow.com/questions/68727351/how-to-disable-graphql-mutation-query-name-suggestions

Magento 2 Override public static method of framework class