nuwave / lighthouse

A framework for serving GraphQL from Laravel
https://lighthouse-php.com
MIT License
3.35k stars 438 forks source link

Custom resolver for Union type not Executing #907

Closed jampack closed 5 years ago

jampack commented 5 years ago

Custom resolver for Union directive not executing

Schema

extend type Query {
    ad(id: ID @eq): Ad @find(model: "App\\Models\\Ad")
    ads: [Ad!]! @paginate(type: "paginator" model: "App\\Models\\Ad")
}

union AdDetail @union(resolveType: "App\\GraphQL\\Unions\\AdDetail@resolveType") =
RoomForRentAd | RoomWantedAd

type Ad{
    id: ID!
    author: User! @belongsTo
    reference_id: String!
    ad_type: AdType! @rename(attribute: "type")
    title: String!
    description: String!
    detail: AdDetail
}

App\GraphQL\Unions\AdDetail.php

<?php

namespace App\GraphQL\Unions;

use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\Log;
use Nuwave\Lighthouse\Schema\TypeRegistry;

class AdDetail
{
    protected $typeRegistry;

    public function __construct(TypeRegistry $typeRegistry)
    {
        $this->typeRegistry = $typeRegistry;
    }

    public function resolveType($rootValue, GraphQLContext $context, ResolveInfo $resolveInfo): Type
    {
        Log::info("test", [$rootValue, $context, $resolveInfo]);
        return $this->typeRegistry->get(class_basename($rootValue));
    }
}

Method 'resolveType' doesn't log anything, leaving it empty doesn't raise any exceptions also exiting inside it doesn't cause any problems too... The 'constructor' is being called and logging data though

Query

query {
  ad(id: "008c5402-fdf1-35c5-9a01-77bb6dbd9b41") {
    author {
      name
      email
    }
    reference_id
    ad_type
    title
    description
    detail {
      __typename
      ... on RoomForRentAd {
        rent
      }
      ... on RoomWantedAd {
        people_male
      }
    }
  }
}

Response

{
  "data": {
    "ad": {
      "author": {
        "name": "Mrs. Velva Howell II",
        "email": null
      },
      "reference_id": "NV976",
      "ad_type": "ROOM_WANTED_AD",
      "title": "Quia laboriosam et et quam qui.",
      "description": "Eos provident a nemo molestias rerum autem quos. Hic et quo vero modi. Sint earum quis ea earum corporis accusantium veritatis. ",
      "detail": null
    }
  }
}

Lighthouse Version: 3.7 Laravel Version: 5.8

jampack commented 5 years ago

Sorry my mistake the field needs to be resolved manually with @method directive.

union UnionType = typeA | typeB

query {
  someField: UnionType @method(name: "method")
}