Ruby GraphQL从查询返回联合类型

pgx2nnw8  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(130)

我想让查询返回联合类型
我的工会类型:

class LeadType < ::Types::BaseUnion
  description "Lead"
  possible_types WebsiteLeadType

  def self.resolve_type(object, _context)
    case object.lead_type
    when "website"
      WebsiteLeadType
    else
      raise "Can't find type for lead"
    end
  end
end

字符串
我尝试在查询中使用类型:

class LeadQuery < ::Queries::BaseQuery
  argument :lead_id, ID, required: true, description: "Lead ID"

  type Types::LeadType, null: true

  def resolve(lead_id:, token:)
    lead = Lead.find(lead_id)
  end
end


但我得到一个错误

NameError:
  uninitialized constant Types::BaseEdge

      edge_type_class(Types::BaseEdge)
                           ^^^^^^^^^^
  Did you mean?  Types::BaseField
# ./app/graphql/types/base_object.rb:3:in `<class:BaseObject>'


可通过以下查询类型使用查询:

class QueryType < ::Types::BaseObject
  field :lead, resolver: LeadQuery
end


我想在其他查询和变化中重用LeadType联合类型,因此resolve_type逻辑需要可重用,并且在一个文件中。

whitzsjs

whitzsjs1#

一个修复方法是在将查询添加到主类型时添加该类型,并将其从解析程序类中移除

class QueryType < ::Types::BaseObject
  field :lead, Types::LeadType, resolver: LeadQuery
end

class LeadQuery < ::Queries::BaseQuery
  argument :lead_id, ID, required: true, description: "Lead ID"

  def resolve(lead_id:, token:)
    lead = Lead.find(lead_id)
  end
end

字符串

相关问题