Povilas Gintutis
Povilas Gintutis

Reputation: 298

how to intercept graphql request in api-platform?

i'm using api-platform 2.3.5 and i can't find a way to intercept a graphQl request.

I mean that let's say i'm making a mutation (update) and want to also log the data or send an email. How do i do that ?

I did read the api-platform documentation, but there's very little about their implementation of graphQl. It does quite a lot automagically.

Events are not yet implemented (https://github.com/api-platform/core/pull/2329)

I also found this - https://github.com/api-platform/core/blob/master/src/GraphQl/Resolver/Factory/ItemMutationResolverFactory.php#L101 but i'd rather not touch it. Is there a simpler way ?

Upvotes: 1

Views: 731

Answers (1)

BernardA
BernardA

Reputation: 1523

I know this is a bit old but if only for reference.

The recommended way with API-Platform's graphql is to use stage. See this documentation.

In the case of the sending an e-mail you can use the serialize stage. See example below for sending email to notify user he has received a message.

<?php

namespace App\Stage;

use ApiPlatform\Core\GraphQl\Resolver\Stage\SerializeStageInterface;
use App\Email\Mailer;

final class SerializeStage implements SerializeStageInterface
{
/**
 * @var Mailer
 */
private $mailer;
private $serializeStage;

public function __construct(
    SerializeStageInterface $serializeStage,
    Mailer $mailer)
{
    $this->serializeStage = $serializeStage;
    $this->mailer = $mailer;
}

/**
 * @param object|iterable|null $itemOrCollection
 */
public function __invoke($itemOrCollection, string $resourceClass, string $operationName, array $context): ?array 
{
    // Call the decorated serialized stage (this syntax calls the __invoke method).
    $serializedObject = ($this->serializeStage)($itemOrCollection, $resourceClass, $operationName, $context);

    // send notification e-mail if creating message
    if ($resourceClass === 'App\Entity\Message' && $operationName === 'create') {
        $this->mailer->sendMessageNotificationEmail($itemOrCollection->getReceiver());
    } 

    return $serializedObject;
}
}

Then we need to decorate the native stage:

/config/services.yaml

    App\Stage\SerializeStage:
    decorates: api_platform.graphql.resolver.stage.serialize

Upvotes: 1

Related Questions