【问题标题】:Can I move my queries out of query_type.rb into their own files/classes?我可以将查询从 query_type.rb 移到他们自己的文件/类中吗?
【发布时间】:2020-05-25 20:37:38
【问题描述】:

通常,在 GraphQL/Rails 中,您有一个类似于以下内容的 query_type.rb 文件:

module Types
  class QueryType < Types::BaseObject
    # Add root-level fields here.
    # They will be entry points for queries on your schema.

    field :test_field, String, null: false do
      description 'Test field'
    end
    def test_field
      'My test field!'
    end
  end
end

我所有的查询都在这个文件中完全实现了。有没有办法做类似mutation_type.rb 的事情并将查询实现范围扩展到其他文件?也许是这样的?:

query_type.rb:

module Types
  class QueryType < Types::BaseObject
    # Add root-level fields here.
    # They will be entry points for queries on your schema.
    field :test_field, String, null: false, query: Types::TestFieldType
  end
end

test_field_type.rb:

module Types
  class TestFieldType < Types::BaseObject
    description 'Test Field'

    def test_field
      'My Test field!'
    end
  end
end

【问题讨论】:

  • 你的意思是喜欢field :test_field, Types::TestFieldType, null: false吗?
  • 我正在寻找一种方法来将我的查询从query_type.rb 提取到他们自己的文件中,就像你对突变所做的那样。在我看来,它使阅读代码更易于管理。

标签: ruby-on-rails ruby graphql graphql-ruby


【解决方案1】:

您可以创建自己的自定义字段类,该类接受任意关键字参数,例如上面的示例中的query

你可以创建:

class MyField
  def self.call
    # implement
  end
end

class Types::ClassBasedField < GraphQL::Schema::Field
  def initialize(*args, query: nil, **kwargs, &block)
    super(*args, **kwargs, &block)

    return unless query

    # some metaprogramming here to define a method that invokes
    # your own query class implementation if provided
    #
    # Maybe something like this (untested)
    define_method(args[0], &query.method(:call))
  end
end

# within BaseObject
field_class Types::ClassBasedField

更多关于如何使用自定义字段类: https://graphql-ruby.org/type_definitions/extensions.html

【讨论】:

    【解决方案2】:

    GraphQL Ruby 支持resolvers,可用于包含解析逻辑。我自己从来没有使用过它,目前还没有设置环境来测试它,但它可能会为您指明正确的方向。

    查看上面链接的解析器文档以获取更多信息。

    # app/graphql/resolvers/base.rb
    module Resolvers
      class Base < GraphQL::Schema::Resolver; end
    end
    
    # app/graphql/resolvers/test_field.rb
    module Resolvers
      class TestField < Resolvers::Base
        type String, null: false
        description 'Test Field'
    
        def resolve
          'My test field!'
        end
      end
    end
    
    # app/graphql/types/query_type.rb
    module Types
      class QueryType < Types::BaseObject
        # Add root-level fields here.
        # They will be entry points for queries on your schema.
        field :test_field, resolver: Resolvers::TestField
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 2010-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多