-
-
Notifications
You must be signed in to change notification settings - Fork 469
Expand file tree
/
Copy pathFindDirective.php
More file actions
84 lines (68 loc) · 2.39 KB
/
Copy pathFindDirective.php
File metadata and controls
84 lines (68 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace Nuwave\Lighthouse\Schema\Directives;
use GraphQL\Error\Error;
use Illuminate\Database\Eloquent\Model;
use Nuwave\Lighthouse\Execution\ResolveInfo;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Select\SelectHelper;
use Nuwave\Lighthouse\Support\Contracts\FieldResolver;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class FindDirective extends BaseDirective implements FieldResolver
{
public static function definition(): string
{
return /** @lang GraphQL */ <<<'GRAPHQL'
"""
Find a model based on the arguments provided.
"""
directive @find(
"""
Specify the class name of the model to use.
This is only needed when the default model detection does not work.
"""
model: String
"""
Apply scopes to the underlying query.
"""
scopes: [String!]
) on FIELD_DEFINITION
GRAPHQL;
}
public function resolveField(FieldValue $fieldValue): FieldValue
{
$fieldValue->setResolver(function ($root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): ?Model {
$builder = $resolveInfo
->enhanceBuilder(
$this->getModelClass()::query(),
$this->directiveArgValue('scopes', [])
);
if (config('lighthouse.optimized_selects')) {
$fieldSelection = array_keys($resolveInfo->getFieldSelection(1));
$selectColumns = SelectHelper::getSelectColumns(
$this->definitionNode,
$fieldSelection,
$this->getModelClass()
);
if (empty($selectColumns)) {
throw new Error('The select column is empty.');
}
$builder = $builder->select($selectColumns);
$model = $builder->getModel();
/** @var string|string[] $keyName */
$keyName = $model->getKeyName();
if (is_string($keyName)) {
$keyName = [$keyName];
}
foreach ($keyName as $name) {
$builder->orderBy($name);
}
}
$results = $builder->get();
if ($results->count() > 1) {
throw new Error('The query returned more than one result.');
}
return $results->first();
});
return $fieldValue;
}
}