我正在使用 rails 和 graphql-ruby gem 构建我的第一个 GraphQL api。到目前为止,它非常简单而且非常棒。
我现在有点被重复代码困住了。我有一个项目管理 Rails 应用程序,它有空间、待办事项(它们属于一个空间)、用户。
我想要实现的是能够查询空间及其待办事项以及当前用户的所有待办事项。对于待办事项,我希望能够使用不同的参数来过滤它们:
完成 - bool 值, 范围 - 字符串(今天或本周), 受让人 - 整数(用户的 Id)
query {
space(id: 5) {
todos(done: false) {
name
done
dueAt
}
}
}
query {
me {
todos(done: false, scope: today) {
name
done
dueAt
}
}
}
这意味着每次我得到字段待办事项时,我都希望能够过滤它们,无论它们是完成的还是今天到期的等等。
我知道如何使用参数并且一切正常,但目前我一遍又一遍地使用相同的编码器。每当我有相同的 todos 字段时,我如何(以及在哪里)提取该代码以使其可重用?
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
到:
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
非常简单!
关于ruby-on-rails - 在 Ruby 中重用 GraphQL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55958893/