2016-11-11 46 views
5

我有一個UserType和一個可以是Writer或Account的可用項。如何用ruby-graphql指定多態類型?

對於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放在多個地方,但我似乎無法弄清楚這一點?

現在有沒有人如何實現這個?

回答

2

該錯誤表示您需要在應用模式中定義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將模型鏈接到類型。或者,您可以在模型上創建引用其類型的類方法或屬性。例如

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