如何使用 graphql-ruby 指定多态类型?

How do I specify polymorphic types with graphql-ruby?

我有一个 UserType 和一个可以是 Writer 或 Account 的 userable。

对于 GraphQL,我想也许我可以像这样使用 UserableUnion:

UserableUnion = GraphQL::UnionType.define do
  name "Userable"
  description "Account or Writer object"
  possible_types [WriterType, AccountType]
end

然后像这样定义我的用户类型:

UserType = GraphQL::ObjectType.define do
  name "User"
  description "A user object"
  field :id, !types.ID
  field :userable, UserableUnion
end

但是我得到了schema contains Interfaces or Unions, so you must define a 'resolve_type (obj, ctx) -> { ... }' function

我试过在多个地方放置 resolve_type,但我似乎无法弄明白?

现在有人知道如何实现吗?

该错误意味着您需要在应用架构中定义 resolve_type 方法。它应该接受 ActiveRecord 模型和上下文,以及 return GraphQL 类型。

AppSchema = GraphQL::Schema.define do
  resolve_type ->(record, ctx) do
    # figure out the GraphQL type from the record (activerecord)
  end
end

您可以实施 this example 将模型链接到类型。或者,您可以在引用其类型的模型上创建 class 方法或属性。例如

class ApplicationRecord < ActiveRecord::Base
  class << self
    attr_accessor :graph_ql_type
  end
end

class Writer < ApplicationRecord
  self.graph_ql_type = WriterType
end

AppSchema = GraphQL::Schema.define do
  resolve_type ->(record, ctx) { record.class.graph_ql_type }
end

现在 GraphQL 中有 UnionType Ruby

https://graphql-ruby.org/type_definitions/unions.html#defining-union-types

它有清晰的示例,说明如何定义您可以使用的 UnionType。

class Types::CommentSubject < Types::BaseUnion
  description "Objects which may be commented on"
  possible_types Types::Post, Types::Image

  # Optional: if this method is defined, it will override `Schema.resolve_type`
  def self.resolve_type(object, context)
    if object.is_a?(BlogPost)
      Types::Post
    else
      Types::Image
    end
  end
end