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

mha*_*190 6 ruby ruby-on-rails graphql

我有一个UserType和一个可用的,可以是一个Writer或帐户.

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

UserableUnion = GraphQL::UnionType.define do
  name "Userable"
  description "Account or Writer object"
  possible_types [WriterType, AccountType]
end
Run Code Online (Sandbox Code Playgroud)

然后像这样定义我的UserType:

UserType = GraphQL::ObjectType.define do
  name "User"
  description "A user object"
  field :id, !types.ID
  field :userable, UserableUnion
end
Run Code Online (Sandbox Code Playgroud)

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

我试过在多个地方放置一个resolve_type,但我似乎无法弄清楚这一点?

现在有人如何实现这个?

Mar*_*ock 6

该错误意味着您需要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
Run Code Online (Sandbox Code Playgroud)

您可以实现将模型链接到类型的示例.或者,您可以在模型上创建引用其类型的类方法或属性.例如

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
Run Code Online (Sandbox Code Playgroud)


Blu*_*nga 5

现在 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
Run Code Online (Sandbox Code Playgroud)