[英]How do I specify polymorphic types with graphql-ruby?
我有一個 UserType 和一個 userable,可以是 Writer 或 Account。
對於 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,但我似乎無法弄清楚這一點?
現在有沒有人如何實現這一點?
該錯誤意味着您需要在應用程序架構中定義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
您可以實現此示例,將模型鏈接到類型。 或者您可以在模型上創建一個類方法或屬性來引用它們的類型。 例如
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
現在 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.