graphqlite icon indicating copy to clipboard operation
graphqlite copied to clipboard

Optional Input Types

Open PhilippSchreiber opened this issue 5 years ago • 2 comments

Hey there, thanks for the best graphql implementation available! I have one problem to report:

I want to have mutations with optional parameters. With String and Int it is working fine. But with a custom input type, e.g. User, it does not work. Here is an example of my mutation:

/**
 * @Mutation()
 * @param User $user
 * @return string
 */
public function doSomething(?User $user = null): string
{
    if (null !== $user) {
        return "no user";       
    }

    return "user";
}

Then I have a factory:

/**
 * @Factory()
 */
public function getUserById(int $id): User
{
    return $this->userManager->findOneById($id);
}

It works fine, when I write two mutations:

mutation DoSomethingWithUser {
  doSomething(user: {id: 1})
}

and

mutation DoSomethingWithoutUser {
  doSomething()
}

But that means that I have to replicate all the mutations that work with or without custom input types. I wished it would be possible to do this for calling the mutation with user = null:

mutation DoSomethingWithUser {
  doSomething(user: {id: null})
}

But then I get this response:

{
  "errors": [
    {
      "message": "Field \"doSomething\" argument \"user\" requires type Int!, found null.",
      "extensions": {
        "category": "graphql"
      },
      "locations": [
        {
          "line": 31,
          "column": 26
        }
      ]
    }
  ]
}

It makes sense, since the Factoy method has a mandatory integer as param. I tried to make this optional and return ?User. But this is not allowed. I then tried to throw an exception but this bubbles to the frontend.

Am I missing something? My workaround now is to use an integer as param and if it is not null get the user by hand – omitting the factory. But it does not feel good.

PhilippSchreiber avatar May 23 '20 16:05 PhilippSchreiber

I'm not 100% sure I understand what you want to do.

Would you like to be able to do something like this?

/**
 * @Factory()
 */
public function getUserById(?int $id): ?User
{
    if ($id === null) {
        return null;
    }
    return $this->userManager->findOneById($id);
}

moufmouf avatar Jun 01 '20 14:06 moufmouf

@PhilippSchreiber did you figure out the issue here?

oojacoboo avatar Mar 29 '21 16:03 oojacoboo