Steve Moretz
Steve Moretz

Reputation: 3138

Laravel Lighthouse get parsed request

I'm new to Php Lighthouse and GraphQL in general.

I'm trying to move an older system written in rest api, to GraphQL.In this older system I use the url to get some stuff done conditionally, for instance if the url starts with /products I load the e-commerce plugin and if it doesn't I don't load it so it's always fast and optimal.

I know that GraphQL has only one endpoint so I can't do this directly here, so I need a way to still be able to activate and deactivate the plugins on each request dynamically.

I thought if I could get a parsed version of the request. for example for:

{
  users{
    data{
      ID,
      display_name
    }
  }
}

If I could somehow get the users then I could load the plugins which are needed for that.

Yet all I could find was:

https://lighthouse-php.com/5/concepts/request-lifecycle.html#request-parsing

Which basically explains that the parsing occurs according to an standard, but doesn't state how we can access the parsed data.

I need some guidance here, if you have a better way than mine I'm totally open to it and it is highly appreciated.

Upvotes: 0

Views: 453

Answers (1)

mostafa
mostafa

Reputation: 196

I suggest you use the Visitor. It is an inspection tool from php-graphql. There is an example of this implementation that you can check in Nuwave\Lighthouse\CacheControl:CacheControlServiceProvider.php.

I believe the only thing that you need is to add this to your boot function in the service provider:

public function boot(Dispatcher $dispatcher): void
    {
        $dispatcher->listen(
            StartExecution::class,
            function (StartExecution $startExecution) {
                $typeInfo = new TypeInfo($startExecution->schema);

                Visitor::visit($startExecution->query, Visitor::visitWithTypeInfo($typeInfo, [
                    NodeKind::FIELD => function (FieldNode $_) use ($typeInfo): void {
                        $field = $typeInfo->getFieldDef();
                        
                        // @phpstan-ignore-next-line can be null, remove ignore with graphql-php 15
                        if (null === $field) {
                            return;
                        }
                        
                        if ($field->name === 'user') {
                            echo 'enable the plugin';
                        }
                    },
                ]));
            }
        );
    }

You can also check the events page, maybe you find a better place to hook into the lifecycle and get the data you need without Visitor.

Upvotes: 1

Related Questions