Ruby on rails 在Ruby中重用GraphQL参数
我正在使用rails和GraphQlRubyGem构建我的第一个GraphQLAPI。到目前为止,它非常简单,非常棒 我现在有点被重复的代码卡住了。我有一个项目管理rails应用程序,它有空间、TODO(它们属于一个空间)、用户 我想要实现的是能够查询空间及其TODO,但也可以查询当前用户的所有TODO,例如。对于TODO,我希望能够使用不同的参数筛选它们: 完成-布尔, 范围-字符串(今天或本周), 受让人-整数(用户Id) 这意味着每次我拿到字段TODO时,我都希望能够过滤它们,无论它们是完成的还是今天到期的,等等 我知道如何使用参数,一切都很好,但目前我得到了相同的编码器一遍又一遍。每次我有相同的todos字段时,我如何(在哪里)提取代码以使其可重用Ruby on rails 在Ruby中重用GraphQL参数,ruby-on-rails,ruby,graphql,Ruby On Rails,Ruby,Graphql,我正在使用rails和GraphQlRubyGem构建我的第一个GraphQLAPI。到目前为止,它非常简单,非常棒 我现在有点被重复的代码卡住了。我有一个项目管理rails应用程序,它有空间、TODO(它们属于一个空间)、用户 我想要实现的是能够查询空间及其TODO,但也可以查询当前用户的所有TODO,例如。对于TODO,我希望能够使用不同的参数筛选它们: 完成-布尔, 范围-字符串(今天或本周), 受让人-整数(用户Id) 这意味着每次我拿到字段TODO时,我都希望能够过滤它们,无论它们是完
field :todos, [TodoType], null: true do
argument :done, Boolean, required: false
argument :scope, String, required: false
argument :limit, Integer, required: false
end
好吧,正如@jklina所说,我最终使用了一个自定义解析器 我改变了:
field :todos, [TodoType], null: true do
argument :done, Boolean, required: false
argument :scope, String, required: false
argument :limit, Integer, required: false
end
致:
并添加了一个解析器:
module Resolvers
class Todos < Resolvers::Base
type [Types::TodoType], null: false
TodoScopes = GraphQL::EnumType.define do
name "TodoScopes"
description "Group of available scopes for todos"
value "TODAY", "List all todos that are due to today", value: :today
value "THISWEEK", "List all todos that are due to the end of the week", value: :this_week
end
argument :done, Boolean, required: false
argument :scope, TodoScopes, required: false
argument :limit, Integer, required: false
argument :assignee_id, Integer, required: false
def resolve(done: nil, scope:nil, limit:5000, assignee_id: nil)
todos = object.todos
# filtering the records...
return todos.limit(limit)
end
end
end
模块解析器
类Todos
很简单 我没有正式的答案,但我知道您可以在GraphQL中使用类似范围的查询。这是一个关于搜索模型的教程:如果您看到方法
normalize_filters
,它只是使用Rails中类似作用域的语法来创建完整的查询。文档在这里提供了一些建议:
field :todos, resolver: Resolvers::Todos, description: "All todos that belong to a given space"
module Resolvers
class Todos < Resolvers::Base
type [Types::TodoType], null: false
TodoScopes = GraphQL::EnumType.define do
name "TodoScopes"
description "Group of available scopes for todos"
value "TODAY", "List all todos that are due to today", value: :today
value "THISWEEK", "List all todos that are due to the end of the week", value: :this_week
end
argument :done, Boolean, required: false
argument :scope, TodoScopes, required: false
argument :limit, Integer, required: false
argument :assignee_id, Integer, required: false
def resolve(done: nil, scope:nil, limit:5000, assignee_id: nil)
todos = object.todos
# filtering the records...
return todos.limit(limit)
end
end
end