Skip to content

[GraphQL] Manage custom queries by using the internal resolvers #2655

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions features/bootstrap/DoctrineContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Document\DummyAggregateOffer as DummyAggregateOfferDocument;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Document\DummyCar as DummyCarDocument;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Document\DummyCarColor as DummyCarColorDocument;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Document\DummyCustomQuery as DummyCustomQueryDocument;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Document\DummyDate as DummyDateDocument;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Document\DummyDtoCustom as DummyDtoCustomDocument;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Document\DummyDtoNoInput as DummyDtoNoInputDocument;
Expand Down Expand Up @@ -60,6 +61,7 @@
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyAggregateOffer;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyCar;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyCarColor;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyCustomQuery;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyDate;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyDtoCustom;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\DummyDtoNoInput;
Expand Down Expand Up @@ -413,6 +415,20 @@ public function thereAreDummyDtoNoOutputObjects(int $nb)
$this->manager->flush();
}

/**
* @Given there are :nb dummyCustomQuery objects
*/
public function thereAreDummyCustomQueryObjects(int $nb)
{
for ($i = 1; $i <= $nb; ++$i) {
$dummyCustomQuery = $this->buildDummyCustomQuery();

$this->manager->persist($dummyCustomQuery);
}

$this->manager->flush();
}

/**
* @Given there are :nb dummy objects with JSON and array data
*/
Expand Down Expand Up @@ -1331,6 +1347,14 @@ private function buildDummyDtoNoOutput()
return $this->isOrm() ? new DummyDtoNoOutput() : new DummyDtoNoOutputDocument();
}

/**
* @return DummyCustomQuery|DummyCustomQueryDocument
*/
private function buildDummyCustomQuery()
{
return $this->isOrm() ? new DummyCustomQuery() : new DummyCustomQueryDocument();
}

/**
* @return DummyFriend|DummyFriendDocument
*/
Expand Down
29 changes: 28 additions & 1 deletion features/graphql/query.feature
Original file line number Diff line number Diff line change
Expand Up @@ -284,11 +284,35 @@ Feature: GraphQL query support
}
"""

Scenario: Custom not retrieved item query
When I send the following GraphQL request:
"""
{
testNotRetrievedItemDummyCustomQuery {
message
}
}
"""
Then the response status code should be 200
And the response should be in JSON
And the header "Content-Type" should be equal to "application/json"
And the JSON should be equal to:
"""
{
"data": {
"testNotRetrievedItemDummyCustomQuery": {
"message": "Success (not retrieved)!"
}
}
}
"""

Scenario: Custom item query
Given there are 2 dummyCustomQuery objects
When I send the following GraphQL request:
"""
{
testItemDummyCustomQuery {
testItemDummyCustomQuery(id: "/dummy_custom_queries/1") {
message
}
}
Expand Down Expand Up @@ -329,6 +353,9 @@ Feature: GraphQL query support
"data": {
"testCollectionDummyCustomQueries": {
"edges": [
{
"node": {"message": "Success!"}
},
{
"node": {"message": "Success!"}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\GraphQl\Resolver\QueryResolverInterface;
use ApiPlatform\Core\GraphQl\Resolver\QueryCollectionResolverInterface;
use ApiPlatform\Core\GraphQl\Resolver\QueryItemResolverInterface;
use ApiPlatform\Core\GraphQl\Type\Definition\TypeInterface as GraphQlTypeInterface;
use Doctrine\Common\Annotations\Annotation;
use Doctrine\ORM\Version;
Expand Down Expand Up @@ -110,7 +111,9 @@ public function load(array $configs, ContainerBuilder $container)
->addTag('api_platform.subresource_data_provider');
$container->registerForAutoconfiguration(FilterInterface::class)
->addTag('api_platform.filter');
$container->registerForAutoconfiguration(QueryResolverInterface::class)
$container->registerForAutoconfiguration(QueryItemResolverInterface::class)
->addTag('api_platform.graphql.query_resolver');
$container->registerForAutoconfiguration(QueryCollectionResolverInterface::class)
->addTag('api_platform.graphql.query_resolver');
$container->registerForAutoconfiguration(GraphQlTypeInterface::class)
->addTag('api_platform.graphql.type');
Expand Down
19 changes: 10 additions & 9 deletions src/Bridge/Symfony/Bundle/Resources/config/graphql.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,18 @@

<!-- Resolvers -->

<service id="api_platform.graphql.resolver.factory.item" class="ApiPlatform\Core\GraphQl\Resolver\Factory\ItemResolverFactory" public="false">
<argument type="service" id="api_platform.iri_converter" />
<argument type="service" id="api_platform.graphql.query_resolver_locator" />
<argument type="service" id="serializer" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="service" id="api_platform.security.resource_access_checker" on-invalid="ignore" />
</service>

<service id="api_platform.graphql.resolver.factory.collection" class="ApiPlatform\Core\GraphQl\Resolver\Factory\CollectionResolverFactory" public="false">
<argument type="service" id="api_platform.collection_data_provider" />
<argument type="service" id="api_platform.subresource_data_provider" />
<argument type="service" id="api_platform.graphql.query_resolver_locator" />
<argument type="service" id="serializer" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="service" id="api_platform.security.resource_access_checker" on-invalid="null" />
Expand All @@ -28,13 +37,6 @@
<argument type="service" id="api_platform.validator" on-invalid="null" />
</service>

<service id="api_platform.graphql.resolver.item" class="ApiPlatform\Core\GraphQl\Resolver\ItemResolver" public="false">
<argument type="service" id="api_platform.iri_converter" />
<argument type="service" id="serializer" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="service" id="api_platform.security.resource_access_checker" on-invalid="ignore" />
</service>

<service id="api_platform.graphql.resolver.resource_field" class="ApiPlatform\Core\GraphQl\Resolver\ResourceFieldResolver" public="false">
<argument type="service" id="api_platform.iri_converter" />
</service>
Expand Down Expand Up @@ -62,11 +64,10 @@
<argument type="service" id="api_platform.metadata.property.metadata_factory" />
<argument type="service" id="api_platform.metadata.resource.name_collection_factory" />
<argument type="service" id="api_platform.metadata.resource.metadata_factory" />
<argument type="service" id="api_platform.graphql.resolver.factory.item" />
<argument type="service" id="api_platform.graphql.resolver.factory.collection" />
<argument type="service" id="api_platform.graphql.resolver.factory.item_mutation" />
<argument type="service" id="api_platform.graphql.resolver.item" />
<argument type="service" id="api_platform.graphql.resolver.resource_field" />
<argument type="service" id="api_platform.graphql.query_resolver_locator" />
<argument type="service" id="api_platform.graphql.types_factory" />
<argument type="service" id="api_platform.filter_locator" />
<argument>%api_platform.collection.pagination.enabled%</argument>
Expand Down
15 changes: 13 additions & 2 deletions src/GraphQl/Resolver/Factory/CollectionResolverFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
use ApiPlatform\Core\DataProvider\SubresourceDataProviderInterface;
use ApiPlatform\Core\Exception\ResourceClassNotSupportedException;
use ApiPlatform\Core\GraphQl\Resolver\FieldsToAttributesTrait;
use ApiPlatform\Core\GraphQl\Resolver\QueryCollectionResolverInterface;
use ApiPlatform\Core\GraphQl\Resolver\ResourceAccessCheckerTrait;
use ApiPlatform\Core\GraphQl\Serializer\ItemNormalizer;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use GraphQL\Error\Error;
use GraphQL\Type\Definition\ResolveInfo;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

Expand All @@ -42,16 +44,18 @@ final class CollectionResolverFactory implements ResolverFactoryInterface

private $collectionDataProvider;
private $subresourceDataProvider;
private $queryResolverLocator;
private $normalizer;
private $resourceAccessChecker;
private $requestStack;
private $paginationEnabled;
private $resourceMetadataFactory;

public function __construct(CollectionDataProviderInterface $collectionDataProvider, SubresourceDataProviderInterface $subresourceDataProvider, NormalizerInterface $normalizer, ResourceMetadataFactoryInterface $resourceMetadataFactory, ResourceAccessCheckerInterface $resourceAccessChecker = null, RequestStack $requestStack = null, bool $paginationEnabled = false)
public function __construct(CollectionDataProviderInterface $collectionDataProvider, SubresourceDataProviderInterface $subresourceDataProvider, ContainerInterface $queryResolverLocator, NormalizerInterface $normalizer, ResourceMetadataFactoryInterface $resourceMetadataFactory, ResourceAccessCheckerInterface $resourceAccessChecker = null, RequestStack $requestStack = null, bool $paginationEnabled = false)
{
$this->subresourceDataProvider = $subresourceDataProvider;
$this->collectionDataProvider = $collectionDataProvider;
$this->subresourceDataProvider = $subresourceDataProvider;
$this->queryResolverLocator = $queryResolverLocator;
$this->normalizer = $normalizer;
$this->resourceAccessChecker = $resourceAccessChecker;
$this->requestStack = $requestStack;
Expand Down Expand Up @@ -87,6 +91,13 @@ public function __invoke(string $resourceClass = null, string $rootClass = null,
$collection = $this->collectionDataProvider->getCollection($resourceClass, null, $dataProviderContext);
}

$queryResolverId = $resourceMetadata->getGraphqlAttribute($operationName ?? 'query', 'collection_query');
if (null !== $queryResolverId) {
/** @var QueryCollectionResolverInterface $queryResolver */
$queryResolver = $this->queryResolverLocator->get($queryResolverId);
$collection = $queryResolver($collection, ['source' => $source, 'args' => $args, 'info' => $info]);
}

$this->canAccess($this->resourceAccessChecker, $resourceMetadata, $resourceClass, $info, $collection, $operationName ?? 'query');

if (!$this->paginationEnabled) {
Expand Down
130 changes: 130 additions & 0 deletions src/GraphQl/Resolver/Factory/ItemResolverFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php

/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

declare(strict_types=1);

namespace ApiPlatform\Core\GraphQl\Resolver\Factory;

use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Exception\ItemNotFoundException;
use ApiPlatform\Core\Exception\RuntimeException;
use ApiPlatform\Core\GraphQl\Resolver\FieldsToAttributesTrait;
use ApiPlatform\Core\GraphQl\Resolver\QueryItemResolverInterface;
use ApiPlatform\Core\GraphQl\Resolver\ResourceAccessCheckerTrait;
use ApiPlatform\Core\GraphQl\Serializer\ItemNormalizer;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
use GraphQL\Type\Definition\ResolveInfo;
use Psr\Container\ContainerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

/**
* Creates a function retrieving an item to resolve a GraphQL query.
*
* @experimental
*
* @author Alan Poulain <[email protected]>
* @author Kévin Dunglas <[email protected]>
*/
final class ItemResolverFactory implements ResolverFactoryInterface
{
use ClassInfoTrait;
use FieldsToAttributesTrait;
use ResourceAccessCheckerTrait;

private $iriConverter;
private $queryResolverLocator;
private $resourceAccessChecker;
private $normalizer;
private $resourceMetadataFactory;

public function __construct(IriConverterInterface $iriConverter, ContainerInterface $queryResolverLocator, NormalizerInterface $normalizer, ResourceMetadataFactoryInterface $resourceMetadataFactory, ResourceAccessCheckerInterface $resourceAccessChecker = null)
{
$this->iriConverter = $iriConverter;
$this->queryResolverLocator = $queryResolverLocator;
$this->normalizer = $normalizer;
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->resourceAccessChecker = $resourceAccessChecker;
}

public function __invoke(?string $resourceClass = null, ?string $rootClass = null, ?string $operationName = null): callable
{
return function ($source, $args, $context, ResolveInfo $info) use ($resourceClass, $operationName) {
// Data already fetched and normalized (field or nested resource)
if (isset($source[$info->fieldName])) {
return $source[$info->fieldName];
}

$baseNormalizationContext = ['attributes' => $this->fieldsToAttributes($info)];
$item = $this->getItem($args, $baseNormalizationContext);
$resourceClass = $this->getResourceClass($item, $resourceClass);

$resourceMetadata = $this->resourceMetadataFactory->create($resourceClass);

$queryResolverId = $resourceMetadata->getGraphqlAttribute($operationName ?? 'query', 'item_query');
if (null !== $queryResolverId) {
/** @var QueryItemResolverInterface $queryResolver */
$queryResolver = $this->queryResolverLocator->get($queryResolverId);
$item = $queryResolver($item, ['source' => $source, 'args' => $args, 'info' => $info]);
$resourceClass = $this->getResourceClass($item, $resourceClass, sprintf('Custom query resolver "%s"', $queryResolverId).' has to return an item of class %s but returned an item of class %s');
}

$this->canAccess($this->resourceAccessChecker, $resourceMetadata, $resourceClass, $info, $item, $operationName ?? 'query');

$normalizationContext = $resourceMetadata->getGraphqlAttribute($operationName ?? 'query', 'normalization_context', [], true);

return $this->normalizer->normalize($item, ItemNormalizer::FORMAT, $normalizationContext + $baseNormalizationContext);
};
}

/**
* @return object|null
*/
private function getItem($args, array $baseNormalizationContext)
{
if (!isset($args['id'])) {
return null;
}

try {
$item = $this->iriConverter->getItemFromIri($args['id'], $baseNormalizationContext);
} catch (ItemNotFoundException $e) {
return null;
}

return $item;
}

/**
* @param object|null $item
*
* @throws RuntimeException
*/
private function getResourceClass($item, ?string $resourceClass, string $errorMessage = 'Resolver only handles items of class %s but retrieved item is of class %s'): ?string
{
if (null === $item) {
return $resourceClass;
}

$itemClass = $this->getObjectClass($item);

if (null === $resourceClass) {
return $itemClass;
}

if ($resourceClass !== $itemClass) {
throw new RuntimeException(sprintf($errorMessage, $resourceClass, $itemClass));
}

return $resourceClass;
}
}
Loading