|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +require __DIR__ . '/vendor/autoload.php'; |
| 4 | + |
| 5 | +use App\Models\Author; |
| 6 | +use App\Models\Track; |
| 7 | +use GraphQL\GraphQL; |
| 8 | +use GraphQL\Utils\BuildSchema; |
| 9 | + |
| 10 | +$typeConfigDecorator = function (array $typeConfig): array { |
| 11 | + // For object types, the typeConfig array contains the name of the type and a closure that returns the fields of the type. |
| 12 | + // |
| 13 | + // For the Query type, it might look like this: |
| 14 | + // [ |
| 15 | + // 'name': 'Query', |
| 16 | + // 'fields': fn () => [...], |
| 17 | + // ], |
| 18 | + switch ($typeConfig['name']) { |
| 19 | + case 'Query': |
| 20 | + $typeConfig['fields'] = function () use ($typeConfig): array { |
| 21 | + $fields = $typeConfig['fields'](); |
| 22 | + $fields['tracksForHome']['resolve'] = fn (): array => Track::all(); |
| 23 | + |
| 24 | + return $fields; |
| 25 | + }; |
| 26 | + |
| 27 | + return $typeConfig; |
| 28 | + case 'Track': |
| 29 | + $typeConfig['fields'] = function () use ($typeConfig): array { |
| 30 | + $fields = $typeConfig['fields'](); |
| 31 | + $fields['author']['resolve'] = fn (array $track): array => Author::find($track['authorId']); |
| 32 | + |
| 33 | + return $fields; |
| 34 | + }; |
| 35 | + |
| 36 | + return $typeConfig; |
| 37 | + } |
| 38 | + |
| 39 | + return $typeConfig; |
| 40 | +}; |
| 41 | +$contents = file_get_contents(__DIR__ . '/schema.graphql'); |
| 42 | +if ($contents === false) { |
| 43 | + throw new RuntimeException('Failed to read schema.graphql.'); |
| 44 | +} |
| 45 | +$schema = BuildSchema::build($contents, $typeConfigDecorator); |
| 46 | + |
| 47 | +$requestBody = file_get_contents('php://input'); |
| 48 | +if ($requestBody === false) { |
| 49 | + throw new RuntimeException('Failed to read php://input.'); |
| 50 | +} |
| 51 | +$parsedBody = json_decode($requestBody, true, 10); |
| 52 | +$queryString = $parsedBody['query']; |
| 53 | + |
| 54 | +$result = GraphQL::executeQuery($schema, $queryString); |
| 55 | + |
| 56 | +header('Content-Type: application/json'); |
| 57 | +echo json_encode($result); |
0 commit comments