2016-11-11 16 views
5

Tôi có một UserType và một userable có thể là Writer hoặc Account.Làm cách nào để chỉ định các loại đa hình với ruby-graphql?

Đối GraphQL I figured có lẽ tôi có thể sử dụng một UserableUnion như thế này:

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

và sau đó xác định loại người dùng của tôi như thế này:

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

Nhưng tôi nhận được schema contains Interfaces or Unions, so you must define a 'resolve_type (obj, ctx) -> { ... }' function

Tôi đã cố gắng đặt một resolve_type ở nhiều nơi, nhưng tôi không thể hình dung điều này?

Hiện tại có ai thực hiện việc này không?

Trả lời

2

Lỗi đó có nghĩa là bạn cần xác định phương thức resolve_type trong lược đồ ứng dụng của mình. Nó sẽ chấp nhận một mô hình ActiveRecord và ngữ cảnh, và trả về một loại GraphQL.

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

Bạn có thể triển khai this example liên kết mô hình với một loại. Hoặc bạn có thể tạo một phương thức hoặc thuộc tính lớp trên các mô hình của bạn tham chiếu đến các kiểu của chúng. ví dụ.

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 
Các vấn đề liên quan