0

通常,在 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并将查询实现范围扩展到其他文件?也许是这样的?:

查询类型.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
4

2 回答 2

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

于 2020-10-06T16:38:58.680 回答
1

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

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

# 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
于 2020-10-06T18:32:46.977 回答