Skip to content

Commit ffbb68b

Browse files
author
Andrii Sudiev
committed
allow promise to be returned in methods
1 parent ef75504 commit ffbb68b

File tree

2 files changed

+21
-17
lines changed

2 files changed

+21
-17
lines changed

Diff for: src/QueryField.php

+16-9
Original file line numberDiff line numberDiff line change
@@ -74,15 +74,7 @@ public function __construct(
7474
$callResolver = function (...$args) use ($originalResolver, $source, $resolver) {
7575
$result = $resolver($source, ...$args);
7676

77-
try {
78-
$this->assertReturnType($result);
79-
} catch (TypeMismatchRuntimeException $e) {
80-
$e->addInfo($this->name, $originalResolver->toString());
81-
82-
throw $e;
83-
}
84-
85-
return $result;
77+
return $this->unwrapReturnType($result, $originalResolver);
8678
};
8779

8880
// GraphQL allows deferring resolving the field's value using promises, i.e. they call the resolve
@@ -98,6 +90,21 @@ public function __construct(
9890
parent::__construct($config);
9991
}
10092

93+
private function unwrapReturnType(mixed $result, ResolverInterface $originalResolver): mixed
94+
{
95+
if ($result instanceof SyncPromise) {
96+
return $result->then(fn ($resolvedValue) => $this->unwrapReturnType($resolvedValue, $originalResolver));
97+
}
98+
try {
99+
$this->assertReturnType($result);
100+
} catch (TypeMismatchRuntimeException $e) {
101+
$e->addInfo($this->name, $originalResolver->toString());
102+
103+
throw $e;
104+
}
105+
return $result;
106+
}
107+
101108
/**
102109
* This method checks the returned value of the resolver to be sure it matches the documented return type.
103110
* We are sure the returned value is of the correct type... except if the return type is type-hinted as an array.

Diff for: tests/Fixtures/Integration/Models/Blog.php

+5-8
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace TheCodingMachine\GraphQLite\Fixtures\Integration\Models;
66

7+
use GraphQL\Deferred;
78
use TheCodingMachine\GraphQLite\Annotations\Field;
89
use TheCodingMachine\GraphQLite\Annotations\Prefetch;
910
use TheCodingMachine\GraphQLite\Annotations\Type;
@@ -35,17 +36,13 @@ public function getPosts(
3536
return $prefetchedPosts[$this->id];
3637
}
3738

38-
/**
39-
* @param Blog[][] $prefetchedSubBlogs
40-
*
41-
* @return Blog[]
42-
*/
43-
#[Field]
39+
/** @param Blog[][] $prefetchedSubBlogs */
40+
#[Field(outputType: '[Blog!]!')]
4441
public function getSubBlogs(
4542
#[Prefetch('prefetchSubBlogs')]
4643
array $prefetchedSubBlogs,
47-
): array {
48-
return $prefetchedSubBlogs[$this->id];
44+
): Deferred {
45+
return new Deferred(fn () => $prefetchedSubBlogs[$this->id]);
4946
}
5047

5148
/**

0 commit comments

Comments
 (0)