【问题标题】:how to intercept graphql request in api-platform?如何在 api-platform 中拦截 graphql 请求?
【发布时间】:2019-06-04 05:47:29
【问题描述】:

我正在使用 api-platform 2.3.5,但我找不到拦截 graphQl 请求的方法。

我的意思是,假设我正在进行突变(更新)并且还想记录数据或发送电子邮件。我该怎么做?

我确实阅读了 api-platform 文档,但是关于他们的 graphQl 实现的内容很少。它会自动完成很多工作。

事件尚未实现 (https://github.com/api-platform/core/pull/2329)

我也发现了这个 - https://github.com/api-platform/core/blob/master/src/GraphQl/Resolver/Factory/ItemMutationResolverFactory.php#L101 但我宁愿不碰它。有没有更简单的方法?

【问题讨论】:

    标签: api-platform.com graphql-php


    【解决方案1】:

    我知道这有点旧,但仅供参考。

    API-Platform 的graphql 推荐的方式是使用stage。见this documentation

    在发送电子邮件的情况下,您可以使用序列化阶段。请参阅下面的示例发送电子邮件以通知用户他已收到消息。

    <?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;
    }
    }
    

    然后我们需要装饰原生舞台:

    /config/services.yaml

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

    【讨论】:

      猜你喜欢
      • 2018-11-02
      • 2021-02-15
      • 2019-03-03
      • 2015-06-25
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2019-11-13
      • 2020-09-20
      相关资源
      最近更新 更多