【问题标题】:Multiple Object Mutation in Ruby GraphQL with GraphQLListRuby GraphQL 中的多对象变异与 GraphQLList
【发布时间】:2020-05-27 07:16:07
【问题描述】:

我有一个带有 GraphQL 的 Rails API 应用程序。我目前正在尝试创建一个 Mutation 来一次更新多个对象。

module Mutations
  module Widgets
    class UpdateWidgets < ::Mutations::BaseMutation
      argument :widgets, [Types::WidgetType, null: true], required: true

      field :widgets, [Types::WidgetType], null: true
      field :errors,  [String], null: true

      def resolve(widgets:)
        # update widgets here
      end
    end
  end
end

我不断收到以下错误:

GraphQL::Schema::InvalidTypeError:
     Argument input on Mutation.updateWidgets is invalid: argument "widgets" type must be a valid input type (Scalar or InputObject), not GraphQL::ListType ([Widget!])

然后我听到了将其设为输入对象的建议,我做了以下操作:

module Types
  class UpdateWidgetsType < Types::BaseInputObject
    description 'Input for multiple widgets'
    argument :widgets, [Types::WidgetType, null: true], required: true
  end
end

现在它是一个输入类型,我调整了要调用的突变

argument :update_widgets, Types::UpdateWidgetType, required: true

反而得到了类似的错误:

GraphQL::Schema::InvalidTypeError:
     Input field UpdateWidgetsInput.updateWidgets is invalid: argument "widgets" type must be a valid input type (Scalar or InputObject), not GraphQL::NonNullType ([Widget]!)

寻找有关如何使其工作的任何见解。

【问题讨论】:

    标签: ruby-on-rails ruby graphql


    【解决方案1】:

    我的一个朋友通过 Twitter 将我推向了这个方向。手动和使用 RSpec 运行了一些测试并使其正常工作。

    最大的问题是过于依赖 Widget 类型而不是完全提取它:

    # app/graphql/types/update_widget_type.rb
    module Types
      class UpdateWidgetType < Types::BaseInputObject
        description 'Input for a Widget'
    
        argument :id, Int, required: true
        argument :name, String, required: false
        # and the rest
      end
    end
    
    # app/graphql/mutations/widgets/update_widgets.rb
    module Mutations
      module Widgets
        class UpdateWidgets < ::Mutations::BaseMutation
    
          argument :update_widgets, [Types::UpdateWidgetType, null: true], required: true
    
          field :widgets, [Types::WidgetType], null: true
          field :errors, [String], null: false
    
          def resolve(update_widgets:)
            # update widgets here
          end
        end
      end
    end
    

    查询将如下所示:

    mutation {
      updateWidgets(input: {
        updateWidgets: [
          {
            id: 1
            name: "Foo"
          },
          {
            id: 2
            name: "Bar"
          }
        ]
      }
    }) {
      widgets {
        id
        name
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 2019-01-02
      • 1970-01-01
      • 2017-03-09
      • 1970-01-01
      • 2019-01-23
      • 2018-07-31
      • 2017-07-27
      • 2023-03-28
      相关资源
      最近更新 更多