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

时间:2016-11-11 05:00:28

标签: ruby-on-rails ruby graphql

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

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

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

然后像这样定义我的UserType:

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,但我似乎无法解决这个问题?

现在有人如何实现这个?

2 个答案:

答案 0 :(得分:5)

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

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

您可以实现将模型链接到类型的this example。或者,您可以在模型上创建引用其类型的类方法或属性。 e.g。

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

答案 1 :(得分:2)

现在在 GraphQL Ruby 中有 UnionType

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