1
<?php
2

3
namespace Nuwave\Lighthouse\Tracing;
4

5
use Closure;
6
use GraphQL\Type\Definition\ResolveInfo;
7
use Nuwave\Lighthouse\Execution\Resolved;
8
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
9
use Nuwave\Lighthouse\Schema\Values\FieldValue;
10
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
11
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
12

13
class TracingDirective extends BaseDirective implements FieldMiddleware
14
{
15
    /**
16
     * @var \Nuwave\Lighthouse\Tracing\Tracing
17
     */
18
    protected $tracing;
19

20 1
    public function __construct(Tracing $tracing)
21
    {
22 1
        $this->tracing = $tracing;
23
    }
24

25 0
    public static function definition(): string
26
    {
27
        return /** @lang GraphQL */ <<<'GRAPHQL'
28 0
"""
29
Do not use this directive directly, it is automatically added to the schema
30
when using the tracing extension.
31
"""
32
directive @tracing on FIELD_DEFINITION
33
GRAPHQL;
34
    }
35

36 1
    public function handleField(FieldValue $fieldValue, Closure $next): FieldValue
37
    {
38
        // Make sure this middleware is applied last
39 1
        $fieldValue = $next($fieldValue);
40

41 1
        $previousResolver = $fieldValue->getResolver();
42

43
        $fieldValue->setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($previousResolver) {
44 1
            $start = $this->tracing->getTime();
45 1
            $result = $previousResolver($root, $args, $context, $resolveInfo);
46 1
            $end = $this->tracing->getTime();
47

48
            Resolved::handle($result, function () use ($resolveInfo, $start, $end): void {
49 1
                $this->tracing->record($resolveInfo, $start, $end);
50 1
            });
51

52 1
            return $result;
53 1
        });
54

55 1
        return $fieldValue;
56
    }
57
}

Read our documentation on viewing source code .

Loading