【问题标题】:Reuse GraphQL arguments in Ruby在 Ruby 中重用 GraphQL 参数
【发布时间】:2019-05-04 16:18:09
【问题描述】:

我正在使用 rails 和 graphql-ruby gem 构建我的第一个 GraphQL api。到目前为止,它非常简单,非常棒。

关于重复代码,我现在有点卡住了。我有一个项目管理 Rails 应用程序,它有空间、待办事项(它们属于一个空间)、用户。

我想要实现的是能够查询空间及其待办事项,以及当前用户的所有待办事项。对于待办事项,我希望能够使用不同的参数过滤它们:

完成 - 布尔值, 范围 - 字符串(今天或本周), 受让人 - 整数(用户 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

【问题讨论】:

标签: ruby-on-rails ruby graphql


【解决方案1】:

好的,正如@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

很简单!

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2018-04-15
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2019-10-06
    • 2020-11-20
    • 1970-01-01
    • 2020-06-23
    相关资源
    最近更新 更多