omegacode/jwt-secured-api-graphql

此扩展包通过 GraphQL 实现扩展了 jwt-secured-api。

0.7.0 2021-05-03 17:56 UTC

This package is auto-updated.

Last update: 2024-09-29 05:36:14 UTC


README

alt text

JWT 保护 API 核心的 GraphQL 集成

...

要求

  • PHP 7.4+
  • composer
  • openssl
  • PHP 扩展 ext-json

集成 GraphQL

添加订阅者

config/services.yaml

  Vendor\MyProject\GraphQLResolverSubscriber:
    arguments:
      - '@service_container'
    tags:
      - 'kernel.event_subscriber'

src/Subscriber/GraphQLResolverSubscriber.php

<?php
declare(strict_types=1);

namespace Vendor\MyProject\Subscriber;

use OmegaCode\JwtSecuredApiGraphQL\Event\ResolverCollectedEvent;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Registry\ResolverRegistry;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Resolver\ResolverInterface;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Vendor\MyProject\QueryResolver;

class GraphQLResolverSubscriber implements EventSubscriberInterface
{
    protected const RESOLVER_CLASSES = [
        QueryResolver::class
    ];

    protected ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ResolverCollectedEvent::NAME => 'onCollected',
        ];
    }

    public function onCollected(ResolverCollectedEvent $event): void
    {
        $registry = $event->getResolverRegistry();
        $registry->clear();
        $this->addResolvers($registry);
    }

    protected function addResolvers(ResolverRegistry $registry): void
    {
        foreach (static::RESOLVER_CLASSES as $resolverClass) {
            /** @var ResolverInterface $resolverInstance */
            $resolverInstance = $this->container->get($resolverClass);
            $registry->add($resolverInstance, $resolverInstance->getType());
        }
    }
}

添加解析器

src/GraphQL/Resolver/QueryResolver.php

<?php

declare(strict_types=1);

namespace Vendor\MyProject\GraphQL\Resolver;

use GraphQL\Type\Definition\ResolveInfo;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Context;
use OmegaCode\JwtSecuredApiGraphQL\GraphQL\Resolver\ResolverInterface;

class QueryResolver implements ResolverInterface
{
    public function __invoke($root, array $args, Context $context, ResolveInfo $info): ?string
    {
        if ($info->fieldName === 'greet') {
            $name = strip_tags($args['name']);

            return "Hello $name";
        }

        return null;
    }

    public function getType(): string
    {
        return 'Query';
    }
}

添加模式

res/graphql/schema.graphql

schema {
    query: Query
}

type Query {
    greet(name: String!): String
}

更新 .env

ENABLE_GRAPHQL_SCHEMA_CACHE="1" 添加到 .env 文件中。