Skip to content

Commit

Permalink
Merge pull request #2 from x-graphql/fix/use-typename-as-alias
Browse files Browse the repository at this point in the history
fix: use __typename as alias
  • Loading branch information
vuongxuongminh authored Feb 20, 2024
2 parents 591440d + af1a2d2 commit 32daca3
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions src/SelectionSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\AST\FragmentDefinitionNode;
use GraphQL\Language\AST\InlineFragmentNode;
use GraphQL\Language\AST\SelectionNode;
use GraphQL\Language\AST\SelectionSetNode;
use GraphQL\Language\Parser;
use GraphQL\Type\Introspection;
Expand All @@ -26,10 +25,13 @@ public static function addTypenameToFragments(array $fragments): void

public static function addTypename(SelectionSetNode $node): void
{
$hasTypenameNode = false;
$shouldAdd = true;

foreach ($node->selections as $selection) {
/** @var SelectionNode $selection */
if ($selection instanceof InlineFragmentNode) {
self::addTypename($selection->selectionSet);
}

if ($selection instanceof FieldNode) {
if (null !== $selection->selectionSet) {
self::addTypename($selection->selectionSet);
Expand All @@ -38,17 +40,16 @@ public static function addTypename(SelectionSetNode $node): void
$name = $selection->name->value;
$alias = $selection->alias?->value;

if ($name === Introspection::TYPE_NAME_FIELD_NAME && null === $alias) {
$hasTypenameNode = true;
if (
$alias === Introspection::TYPE_NAME_FIELD_NAME
|| ($name === Introspection::TYPE_NAME_FIELD_NAME && null === $alias)
) {
$shouldAdd = false;
}
}

if ($selection instanceof InlineFragmentNode) {
self::addTypename($selection->selectionSet);
}
}

if (false === $hasTypenameNode) {
if ($shouldAdd) {
$node->selections[] = Parser::field(Introspection::TYPE_NAME_FIELD_NAME);
}
}
Expand Down

0 comments on commit 32daca3

Please sign in to comment.