如何在Rails中正确使用GraphQL JSON Scalar并解决查询报错
解决Rails GraphQL中
home_data字段的JSON返回问题 问题出在你定义的home_data字段没有指定解析逻辑:GraphQL默认会尝试从当前对象中读取home_data属性或调用home_data方法,但你的原始数据结构里并没有这个属性,只有lead下的home节点,所以查询时会报错。
要实现需求,只需要给home_data字段添加resolve块,手动指定返回的JSON结构即可:
修改后的LeadType代码:
module Types class LeadType < Types::BaseObject graphql_name 'Lead' description 'A lead data query selection' field :first_name, String, null: true field :last_name, String, null: true field :email, String, null: true field :gender, String, null: true field :errors, [String], null: true field :success, String, null: true field :lead, Types::LeadType, null: true # 添加resolve逻辑,从对象的lead节点中提取home数据 field :home_data, GraphQL::Types::JSON, null: false do resolve ->(obj, _args, _ctx) { # 根据你的原始数据结构,从obj中取出lead下的home # 如果obj是ActiveRecord实例,可调整为 obj.lead&.home obj.dig("lead", "home") } end end end
说明:
resolve块中的obj是当前LeadType对应的数据源对象(即你提供的原始哈希数据)。- 使用
dig方法可安全嵌套取值,避免因节点不存在报错;若确定lead和home一定存在,也可直接写obj["lead"]["home"]。 - 如果数据源是ActiveRecord模型实例,只需把取值逻辑改成模型对应的关联或属性调用即可。
调整后,在GraphQL Playground中查询homeData字段时,就能返回你需要的home结构数据。
内容的提问来源于stack exchange,提问作者theKid
相关产品推荐
相关产品推荐

