Laravel 5.7:Lighthouse GraphQL联合解析器

时间:2019-02-07 00:19:31

标签: php laravel graphql

我目前正在使用Lighthouse GraphQL将REST api迁移到GraphQL,我需要有关如何实现 Union 的示例。以下是我要实现的内容:

query {
  me {
    username
    favorite {
      ... on Artist {
        name
      }
      ... on Album {
        title
      }
      ... on Song {
        title
      }
    }
  }
}
type User {
      id: ID!
      first_name: String
      last_name: String
      favorite: [Favorite!] @field(resolver: "App\\Http\\GraphQL\\Types\\UserAttributes@favorite")
    }

    union Favorite @union(resolver: "App\\Http\\GraphQL\\Unions\\Favorite@resolveType") = Artist | Album | Song
class Favorite
{
    /** @var TypeRegistry */
    protected $typeRegistry;

    /**
     * @param TypeRegistry $typeRegistry
     */
    public function __construct(TypeRegistry $typeRegistry)
    {
        $this->typeRegistry = $typeRegistry;
    }

    /**
     * Decide which GraphQL type a resolved value has.
     *
     * @param $rootValue The value that was resolved by the field. Usually an Eloquent model.
     * @param $context
     * @param ResolveInfo $info
     *
     * @return Type
     */
    public function resolveType($rootValue, $context, ResolveInfo $info): Type
    {
        // Default to getting a type with the same name as the passed in root value
        // TODO implement your own resolver logic - if the default is fine, just delete this class
        return $this->typeRegistry->get(class_basename($rootValue));
    }
}

class UserAttributes
{
    public function favorite()
    {
        // How do i implement this....
    }
}

注意::我已经有了(艺术家,专辑,歌曲)的graphql类型,我该如何实现联合。

0 个答案:

没有答案