Skip to content

Commit

Permalink
allow promise to be returned in methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrii Sudiev committed Sep 26, 2024
1 parent ef75504 commit ffbb68b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 17 deletions.
25 changes: 16 additions & 9 deletions src/QueryField.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,7 @@ public function __construct(
$callResolver = function (...$args) use ($originalResolver, $source, $resolver) {
$result = $resolver($source, ...$args);

try {
$this->assertReturnType($result);
} catch (TypeMismatchRuntimeException $e) {
$e->addInfo($this->name, $originalResolver->toString());

throw $e;
}

return $result;
return $this->unwrapReturnType($result, $originalResolver);
};

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

private function unwrapReturnType(mixed $result, ResolverInterface $originalResolver): mixed
{
if ($result instanceof SyncPromise) {
return $result->then(fn ($resolvedValue) => $this->unwrapReturnType($resolvedValue, $originalResolver));
}
try {
$this->assertReturnType($result);
} catch (TypeMismatchRuntimeException $e) {
$e->addInfo($this->name, $originalResolver->toString());

throw $e;
}
return $result;
}

/**
* This method checks the returned value of the resolver to be sure it matches the documented return type.
* We are sure the returned value is of the correct type... except if the return type is type-hinted as an array.
Expand Down
13 changes: 5 additions & 8 deletions tests/Fixtures/Integration/Models/Blog.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace TheCodingMachine\GraphQLite\Fixtures\Integration\Models;

use GraphQL\Deferred;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Prefetch;
use TheCodingMachine\GraphQLite\Annotations\Type;
Expand Down Expand Up @@ -35,17 +36,13 @@ public function getPosts(
return $prefetchedPosts[$this->id];
}

/**
* @param Blog[][] $prefetchedSubBlogs
*
* @return Blog[]
*/
#[Field]
/** @param Blog[][] $prefetchedSubBlogs */
#[Field(outputType: '[Blog!]!')]
public function getSubBlogs(
#[Prefetch('prefetchSubBlogs')]
array $prefetchedSubBlogs,
): array {
return $prefetchedSubBlogs[$this->id];
): Deferred {
return new Deferred(fn () => $prefetchedSubBlogs[$this->id]);
}

/**
Expand Down

0 comments on commit ffbb68b

Please sign in to comment.