Custom producers
type Query {
...
currentUser: User
...
}
type User {
id: Int
name: String
}<?php
namespace Drupal\example\Plugin\GraphQL\DataProducer;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\graphql\Attribute\DataProducer;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Gets the ID of current user.
*/
#[DataProducer(
id: 'current_user',
name: new TranslatableMarkup('Current user'),
description: new TranslatableMarkup('Current logged in user.'),
produces: new ContextDefinition(
data_type: 'integer',
label: new TranslatableMarkup('Current user ID'),
),
)]
class CurrentUser extends DataProducerPluginBase implements ContainerFactoryPluginInterface {
/**
* The current user.
*/
protected AccountInterface $currentUser;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user')
);
}
/**
* UserRegister constructor.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param array $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
*/
public function __construct(array $configuration, string $plugin_id, array $plugin_definition, AccountInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
}
/**
* Returns current user id.
*
* @return int
* The current user id.
*/
public function resolve() {
return $this->currentUser->id();
}
}Last updated
Was this helpful?