ruby-on-rails - Ruby graphql 如何定义不是 Active Record 的对象类型?
问题描述
我想创建一个不在 ActiveRecord 中的 MentionType。当查询 SummaryCommentType 时,我想用它返回 MentionType。但我不知道该怎么做。
我对 graphql 完全陌生。对不起我的英语不好。
这是我的代码
module Types
class MentionType < Types::BaseObject
field :id, Integer, null: false
field :name, String, null: false
end
end
module Types
class SummaryCommentType < Types::BaseObject
field :id, Integer, null: false
field :summary_id, Integer, null: false
field :comment_status, Integer, null: false
field :curator_id, Integer, null: true
field :curator, CuratorType, null: true
field :total_like, Integer, null: true
field :total_dislike, Integer, null: true
field :comment_desc, String, null: true
field :parent_comment_key, Integer, null: true
field :created_at, GraphQL::Types::ISO8601DateTime, null: true
field :updated_at, GraphQL::Types::ISO8601DateTime, null: true
field :sub_comment_count, Integer, null: true
field :summary_comment_sticker, SummaryCommentStickerType, null: true
field :mention, [MentionType.graphql_definition], null:true do
argument :comment_id, Integer, required: true
end
def mention(comment_id:)
comment = SummaryComment.where(id: self.object.id)
# to do put logic here to query mention by comment
# ....
return mention
end
end
end
解决方案
从 GraphQL 查询返回的对象不需要是 ActiveRecord 对象,它们只需要映射到您的字段名称的方法,或者您的字段需要具有可以从对象中提取所需数据的方法。
这是一个使用几种不同方式转换为类型的示例:
module Types
class MentionType < BaseObject
field :id, Integer, null: false
field :name, String, null: false
field :name_upper, String, null: false
def name_upper
if object.is_a?(Hash)
object[:name].upcase
else
object.name.upcase
end
end
end
end
module Types
class QueryType < Types::BaseObject
field :mentions, [MentionType], null: true
def mentions
[
Struct.new(:id, :name).new(1, 'Struct'),
OpenStruct.new(id: 2, name: 'OpenStruct'),
{ id: 3, name: 'Hash' },
CustomObject.new(id: 4, name: 'CustomObject'),
]
end
class CustomObject
def initialize(attrs)
@attrs = attrs
end
def id
@attrs[:id]
end
def name
@attrs[:name]
end
end
end
end
询问:
query {
mentions {
id
name
nameUpper
}
}
结果:
{
"data": {
"mentions": [
{
"id": 1,
"name": "Struct",
"nameUpper": "STRUCT"
},
{
"id": 2,
"name": "OpenStruct",
"nameUpper": "OPENSTRUCT"
},
{
"id": 3,
"name": "Hash",
"nameUpper": "HASH"
},
{
"id": 4,
"name": "CustomObject",
"nameUpper": "CUSTOMOBJECT"
}
]
}
}
推荐阅读
- hyperledger-fabric - Hyperledger Fabric 资产/数据可以是十进制值还是只有整数?
- c# - 将英国格式的字符串 DateTime ("dd/MM/yyyy") 转换为文化可能发生变化的有效 DateTime
- amazon-web-services - Fn::GetOptionSetting 在 AWS ElasticBeanstalk 中不起作用
- c# - RABBITMQ C# 在控制台上运行良好,但不适用于服务
- c - 函数“池”的隐式声明在 C99 中无效
- python - 即使我可以将绘图保存为 png 文件,matplotlib 绘图也不会显示
- node.js - 即使查询遵循文档,Elasticsearch 也会引发有关格式错误的通配符查询的错误
- c# - String.Join 和/或 Enumerable.Aggregate
EntityFramework 中的支持 - javascript - 从 html 表中删除下拉列表
- azure - 是否可以使用 1 个输出绑定在 cosmosDB 中创建 2 个或更多文档