How to specify polymorphic types with ruby-graphql?

I have a UserType and a custom one that can be Writer or Account.

For GraphQL, I assumed that I could use UserableUnion as follows:

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

and then define my UserType as follows:

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

But I get schema contains Interfaces or Unions, so you must define a 'resolve_type (obj, ctx) -> { ... }' function

I tried putting resol_type in several places, but I can't figure it out?

Can anyone implement this now?

+5
source share
1 answer

This error means that you need to define the resolve_type method in your application schema. It should accept the ActiveRecord model and context and return the GraphQL type.

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

You can either implement this example , which associates a model with a type. Or you can create a method or class attribute on your models that relate to their types. eg.

 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 
+2
source

Source: https://habr.com/ru/post/1259575/


All Articles