View source
<?php
namespace Drupal\graphql_examples\Plugin\GraphQL\Schema;
use Drupal\graphql\GraphQL\ResolverBuilder;
use Drupal\graphql\GraphQL\ResolverRegistry;
use Drupal\graphql\Plugin\GraphQL\Schema\SdlSchemaPluginBase;
use Drupal\graphql_examples\Wrappers\QueryConnection;
class ExampleSchema extends SdlSchemaPluginBase {
public function getResolverRegistry() {
$builder = new ResolverBuilder();
$registry = new ResolverRegistry();
$this
->addQueryFields($registry, $builder);
$this
->addArticleFields($registry, $builder);
$this
->addConnectionFields('ArticleConnection', $registry, $builder);
return $registry;
}
protected function addArticleFields(ResolverRegistry $registry, ResolverBuilder $builder) : void {
$registry
->addFieldResolver('Article', 'id', $builder
->produce('entity_id')
->map('entity', $builder
->fromParent()));
$registry
->addFieldResolver('Article', 'title', $builder
->compose($builder
->produce('entity_label')
->map('entity', $builder
->fromParent()), $builder
->produce('uppercase')
->map('string', $builder
->fromParent())));
$registry
->addFieldResolver('Article', 'author', $builder
->compose($builder
->produce('entity_owner')
->map('entity', $builder
->fromParent()), $builder
->produce('entity_label')
->map('entity', $builder
->fromParent())));
}
protected function addQueryFields(ResolverRegistry $registry, ResolverBuilder $builder) : void {
$registry
->addFieldResolver('Query', 'article', $builder
->produce('entity_load')
->map('type', $builder
->fromValue('node'))
->map('bundles', $builder
->fromValue([
'article',
]))
->map('id', $builder
->fromArgument('id')));
$registry
->addFieldResolver('Query', 'articles', $builder
->produce('query_articles')
->map('offset', $builder
->fromArgument('offset'))
->map('limit', $builder
->fromArgument('limit')));
}
protected function addConnectionFields($type, ResolverRegistry $registry, ResolverBuilder $builder) : void {
$registry
->addFieldResolver($type, 'total', $builder
->callback(function (QueryConnection $connection) {
return $connection
->total();
}));
$registry
->addFieldResolver($type, 'items', $builder
->callback(function (QueryConnection $connection) {
return $connection
->items();
}));
}
}