首页 > 解决方案 > 如何使用传递给 Graphql ruby​​ 字段的参数来转换结果?

问题描述

我正在寻找类似于 graphql 教程中所做的事情:https ://graphql.org/learn/queries/#arguments

我想将英尺/米传递给缩放器字段以转换返回的结果。

{
  human(id: "1000") {
    name
    height(unit: FOOT)
  }
}

我不知道如何使用 graphql-ruby 在 ruby​​ 中做到这一点。

我目前有一个看起来像这样的类型:

class Types::Human < Types::BaseObject

  field :id, ID, null: false
  field :height, Int, null: true do
     argument :unit, String, required: false
  end

  def height(unit: nil)

  #what do I do here to access the current value of height so I can use unit to transform the result?

  end
end

我发现每个返回的实例都会调用解析器方法(高度)......但我不知道如何访问当前值。

谢谢

标签: rubygraphqlgraphql-ruby

解决方案


当您在类型定义中定义解析方法时,Graphql Ruby 假定该方法将解析该值。因此,在您当前的方法def height(unit: nil)运行时,它不知道当前的高度值是多少,因为它希望您定义它。

相反,您想要做的是将解析方法移动到为该Human类型返回的模型/对象。例如,在 Rails 中,您可以这样做:

# app/graphql/types/human_type.rb
class Types::Human < Types::BaseObject

  field :id, ID, null: false
  field :height, Int, null: true do
    argument :unit, String, required: false
  end

end
# app/models/human.rb
class Human < ApplicationRecord

  def height(unit: nil)
    # access to height with self[:height]. 
    # You must use self[:height] so as to access the height property
    # and not call the method you defined.  Note: This overrides the
    # getter for height.
  end
end

然后, GraphQL Ruby 将调用.height传递给它的人类实例。


推荐阅读