2016-11-11 1 views
5

私は、ユーザータイプと、ライターまたはアカウントとなるユーザー可能なユーザーを持っています。 GraphQLについてはruby​​-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

このエラーは、アプリスキーマで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 
関連する問題