Cannot query field in GraphQL (Platform API, Symfony)

I am working with Symfony and Platform API to implement a GraphQL API. My goal is to expose different fields, depending on whether the user is logged in. The email should only be displayed if the user is logged in and is the user. Therefore I added the group user:read:self.

/**
 * @ORMColumn(type="string", length=180, unique=true)
 * @Groups({"user:read:self"})
 */
private $email;

Then I implemented a normalizer which adds the group to the context if the user is logged in:

public function normalize($object, string $format = null, array $context = [])
{
    echo "test";

    // checks whether the currently logged in user is
    // this user

    $isCurrentUser = $this->currentUser() == $object;

    if ($isCurrentUser) {
        $context['groups'][] = 'user:read:self';
    }

    $context[self::ALREADY_CALLED] = true;

    return $this->normalizer->normalize($object, $format, $context);
}

The normalizer is in fact getting called for the JSON API and GraphQL API. This works in the JSON API:

{
  "@context": "/api/contexts/User",
  "@id": "/api/users",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/api/users/1",
      "@type": "User",
      "email": "[email protected]",
      "animals": [],
      "friends": []
    },
    {
      "@id": "/api/users/2",
      "@type": "User",
      "animals": [],
      "friends": []
    }
  ],
  "hydra:totalItems": 2
}

I am logged in as user with id 1 and I can see the email. I can’t see the email of user 2.

Then in GraphQLi I query the following and an error, even though I am logged in as user 1. I checked that the normalizer is getting called for the GraphQL query. The normalizer works and adds the group, however it appears that GraphQL does not read the context correctly:

{
  user(id: "/api/users/1") {
    email
  }
}

...
"message": "Cannot query field "email" on type "User".",
...

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

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