mghoneimy/php-graphql-client

Empty string mutation variables handled as null

carlosolivas opened this issue · 3 comments

Hello, I think there is a problem on how empty strings are handled, they are sent as null to the server.

This is the inout I'm sending:

$mutation->setVariables([
        new Variable('input', $input_type, true)
    ])
    ->setArguments(['input' => '$input']);

Which generates the following request:

'query' => 'mutation($input: UpdateHotelInput!) {
updateHotel(input: $input) {
id
}
}',
  'variables' => 
  array (
    'input' => 
    array (
      'id' => '5',
      'settings' => 
      array (
        'syncWithoutDetaching' => 
        array (
          0 => 
          array (
            'id' => 35,
            'value' => '',
          ),
        ),
      ),
    ),
  )

But I'm getting this error from the server:

Expected non-nullable type String! not to be null at value.settings.syncWithoutDetaching[0].value.

I hope you can help me

Thanks

Carlos

Hello,
Are you passing variables along with the query when you run it on the server using the client?

Yes, I am. The problem is when variables have empty string values, they are sent to the GraphQL server as null.

This is the function I use to construct the mutation and set variables:

/**
     * Make an api call to GraphQL endpoint mutation with input argument
     *
     * @param \GraphQL\Mutation $mutation
     * @param string $input_type
     * @param array $input
     * @return Array
     * @throws \Graphql\Exception\QueryError
     **/
    public function graphqlMutation(Mutation $mutation, $input_type, $input=[])
    {
        $url = $this->getUrl(config('system.api.urls.graphql'));

        // Add input to mutation
        $mutation->setVariables([
                new Variable('input', $input_type, true)
            ])
            ->setArguments(['input' => '$input']);

        $client = new Client($url, [ 'Authorization' => "Bearer ".$this->getAccessToken() ]);
        $response = $client->runQuery($mutation, true, ['input' => $input]);

        return $response->getData();
    }

I have personally tested this to verify the behavior and I can assure you that the package does not convert empty strings into nulls when converting variables parameter to json before sending the request to the API server.

Also, for reference, this is where the conversion happens:
https://github.com/mghoneimy/php-graphql-client/blob/master/src/Client.php#L122

The package uses the json_encode method, which is the PHP default method for converting arrays / objects to json arrays / objects. It's impossible that this method would have such a bug.

I'm very confident that the error you are experiencing is not because the package is passing a null in the value object to your GraphQL API, but that the API server you are hitting only allows non-empty strings for this update operation.

You should follow up with the API maintainers, meanwhile, I will close this issue.