drupal-graphql / graphql

GraphQL integration for Drupal 9/10
286 stars 202 forks source link

Is the CustomProducers documentation complete? #1288

Open laurencefass opened 2 years ago

laurencefass commented 2 years ago

Im following through the documentation here: https://drupal-graphql.gitbook.io/graphql/data-producers/custom

All looks good until the last sentence. "(For this to actually work we would need to add resolvers to the User object to resolve the id and name properties)."

Is that explained somewhere else? Could that be included in this page for a complete working example?

Cryt1c commented 2 years ago

Hi @laurencefass ,

there is now a DataProducer that loads the current user included in the module: https://github.com/drupal-graphql/graphql/blob/0570f8f0e4d790698aee97121d68e7d3bf97770a/src/Plugin/GraphQL/DataProducer/User/CurrentUser.php

In contrast to the documentation it returns the user entity instead of only the id. Therefore you can setup your resolvers the following way:

    $registry->addFieldResolver('Query', 'currentUser', $builder->compose(
      $builder->produce('current_user')
    ));

    $registry->addFieldResolver('User', 'id', $builder->callback(function ($account) {
      /** @var \Drupal\Core\Session\AccountProxyInterface $account */
      return $account->id();
    }));

    $registry->addFieldResolver('User', 'name', $builder->callback(function ($account) {
      /** @var \Drupal\Core\Session\AccountProxyInterface $account */
      return $account->getAccountName();
    }));
laurencefass commented 2 years ago

Thank you.

May I ask: Is there a reason why a lot of data producers have been included in the isntallation, but default resolvers arent?

Seeing as they are both mandatory, would it make any sense to include producer-resolver pairs in the default install?

Could the resolver code you provided be included in the default installation, along with resolvers for pages, articles, default menus (or possibly resolvers for all of the default included producers). to provide both an immediate template for developers to extend and alter, and a minimal API for clients to consume?

Cryt1c commented 2 years ago

I think the idea behind the module is to provide full flexibility but still provide some building blocks (DataProducers) for the API. How the DataProducers are wired up (Resolvers), in the end, is open for the developer to decide. This is due to the various use cases that are out there.

We can provide the information on resolver best practices in documenetation instead of putting it to the core module. As an addition we could also extend the graphql_example module.

laurencefass commented 2 years ago

+1 for adding to graphql_example module. It would give me far greater confidence to have a set of sensible defaults to start with.

Could this include resolvers to enable CRUD for all default producers included in GraphQL core This would certainly bring GraphQL on par with core REST and JSON:API