ruby - 如何使用传递给 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
我发现每个返回的实例都会调用解析器方法(高度)......但我不知道如何访问当前值。
谢谢
解决方案
当您在类型定义中定义解析方法时,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
传递给它的人类实例。
推荐阅读
- c# - Xamarin Forms Android Web View with CustomWebViewClient stops working after loading certain site
- java - 创建新实体时获取连接表
- qt - QML ListView contentHeight 属性值不正确
- google-sheets - 将 Google 表单上的两个响应之一设为可点击
- reactjs - 即使用户不在页面上,在哪里保持 socket.on 始终在监听
- sql - 如何根据sql server中的行数动态分区表?
- c# - Asp.Net Core 3.0 与 Api 集成测试的问题
- mlflow - MLFlow 如何将后端存储 uri 从文件存储更改为数据库
- networking - 为什么只使用 MAC 地址将数据包传输到设备?
- javascript - 如何根据定义要插入对象的字段路径的字符串更新 javascript/json 对象