Sha256: 1f618d985a8d563546cbc16bee702faad05bf29041686ebb0c347fabb9a0f7e7

Contents?: true

Size: 1.85 KB

Versions: 9

Compression:

Stored size: 1.85 KB

Contents

module GraphQL::Models
  class Mutator
    attr_accessor :field_map, :root_model, :inputs, :context

    def initialize(field_map, root_model, inputs, context)
      @field_map = field_map
      @root_model = root_model
      @inputs = inputs
      @context = context
    end

    def apply_changes
      fail StandardError.new("Called apply_changes twice for the same mutator") if @all_changes
      @all_changes = MutationHelpers.apply_changes(field_map, root_model, inputs, context)
      changed_models
    end

    def changed_models
      fail StandardError.new("Need to call apply_changes before #{__method__}") unless @all_changes
      @all_changes.map { |c| c[:model_instance] }.uniq
    end

    def validate!
      fail StandardError.new("Need to call apply_changes before #{__method__}") unless @all_changes
      MutationHelpers.validate_changes(inputs, field_map, root_model, context, @all_changes)
    end

    def authorize!
      fail StandardError.new("Need to call apply_changes before #{__method__}") unless @all_changes
      MutationHelpers.authorize_changes(context, @all_changes)
    end

    def save!
      fail StandardError.new("Need to call apply_changes before #{__method__}") unless @all_changes

      ActiveRecord::Base.transaction(requires_new: true) do
        changed_models.each do |model|
          next if model.destroyed?

          if model.marked_for_destruction?
            model.destroy
          else
            model.save!
          end
        end

        changed_models.reject(&:destroyed?)
      end
    end
  end

  class MutatorDefinition
    attr_accessor :field_map

    def initialize(model_type, null_behavior:)
      @field_map = MutationFieldMap.new(model_type, find_by: nil, null_behavior: null_behavior)
    end

    def mutator(root_model, inputs, context)
      Mutator.new(field_map, root_model, inputs, context)
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
graphql-activerecord-0.10.0 lib/graphql/models/mutator.rb
graphql-activerecord-0.10.0.pre.alpha3 lib/graphql/models/mutator.rb
graphql-activerecord-0.10.0.pre.alpha2 lib/graphql/models/mutator.rb
graphql-activerecord-0.10.0.pre.alpha1 lib/graphql/models/mutator.rb
graphql-activerecord-0.9.1 lib/graphql/models/mutator.rb
graphql-activerecord-0.9.0 lib/graphql/models/mutator.rb
graphql-activerecord-0.8.0 lib/graphql/models/mutator.rb
graphql-activerecord-0.7.3 lib/graphql/models/mutator.rb
graphql-activerecord-0.7.2 lib/graphql/models/mutator.rb