ruby-on-rails - 在 Ruby 中重用 GraphQL 参数

标签 ruby-on-rails ruby graphql

我正在使用 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/

相关文章:

html - 在同一个 html 页面中使用两个不同的 css

ruby-on-rails - 我可以强制 Rails 自动加载命名空间而不嵌套在文件夹中吗?

ruby-on-rails - 通过 CORS 策略允许任何内容

ruby - 单行代码输出?

Angular 获取 HTTP 请求的响应大小

javascript - 如何为 Gatsby 提供 GraphQL 模式

ruby-on-rails - 事件存储/清理文件 url

ruby - 脚本文本 ruby​​ 中的 JSON 解析错误

Ruby Nokogiri 解析 HTML 表格

graphql - Wordpress Gatsby - 我如何访问 graphql 中的 ACF 关系内容,或以其他方式