Sha256: 449d1fe00a00091533ccecd6260cc0b95c787a9395332243391c08cbfe161c60

Contents?: true

Size: 1.29 KB

Versions: 9

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module LightServiceExt
  class ApplicationValidatorAction < ApplicationAction
    expects :input
    promises :params, :errors

    executed do |context|
      validator = map_and_validate_inputs(context)
      context.add_params(**validator.to_h)
      context.add_errors!(**validator.errors.to_h)
    end

    class << self
      def inherited(base)
        super
        base.extend ClassMethods
      end

      private

      # Fetches params mapper & contract from the action that was actually invoked
      # then validates against these and returns the contract results
      def map_and_validate_inputs(context)
        invoked_action = context[:invoked_action]

        mapped_params = invoked_action.params_mapper_class.map_from(context)
        invoked_action.contract_class.new.call(mapped_params)
      end
    end

    class NullContract < ApplicationContract
      params { {} }
    end

    NullMapper =
      Struct.new(:ctx) do
        def self.map_from(context)
          context[:input]
        end
      end

    module ClassMethods
      attr_writer :contract_class, :params_mapper_class

      def contract_class
        @contract_class ||= NullContract
      end

      def params_mapper_class
        @params_mapper_class ||= NullMapper
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
light-service-ext-0.1.11 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.10 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.9 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.8 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.7 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.6 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.5 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.4 lib/light-service-ext/application_validator_action.rb
light-service-ext-0.1.3 lib/light-service-ext/application_validator_action.rb