Sha256: 1907112b9a0f4f59d6b16aae1c7e352bd99e8ef298c3f58edcfc262ddf1ab9bd

Contents?: true

Size: 1.9 KB

Versions: 4

Compression:

Stored size: 1.9 KB

Contents

# frozen_string_literal: true

module ConvenientService
  module Service
    module Plugins
      module HasJSendResultParamsValidations
        module UsingDryValidation
          class Middleware < MethodChainMiddleware
            intended_for :result, entity: :service

            ##
            # @return [ConvenientService::Service::Plugins::HasJSendResult::Entities::Result]
            #
            def next(...)
              return entity.public_send(status, data: errors, message: errors.first.to_a.map(&:to_s).join(" ")) if errors.any?

              chain.next(...)
            end

            private

            ##
            # @return [Hash{Symbol => Object}]
            #
            # @internal
            #   NOTE: An example of `Dry::Validation::Contract` usage.
            #   https://dry-rb.org/gems/dry-validation/1.8/#quick-start
            #
            #   TODO: Return one or all errors?
            #
            def errors
              @errors ||= resolve_errors
            end

            ##
            # @return [Hash{Symbol => Object}]
            #
            def constructor_kwargs
              @constructor_kwargs ||= entity.constructor_arguments.kwargs
            end

            ##
            # @return [Dry::Validation::Contract]
            #
            def contract
              @contract ||= entity.class.contract
            end

            ##
            # @return [Hash{Symbol => Object}]
            #
            def resolve_errors
              return {} unless contract.schema

              contract.new
                .call(constructor_kwargs)
                .errors
                .to_h
                .transform_values(&:first)
            end

            ##
            # @return [Symbol]
            #
            def status
              middleware_arguments.kwargs.fetch(:status) { :error }
            end
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
convenient_service-0.17.0 lib/convenient_service/service/plugins/has_j_send_result_params_validations/using_dry_validation/middleware.rb
convenient_service-0.16.0 lib/convenient_service/service/plugins/has_j_send_result_params_validations/using_dry_validation/middleware.rb
convenient_service-0.15.0 lib/convenient_service/service/plugins/has_j_send_result_params_validations/using_dry_validation/middleware.rb
convenient_service-0.14.0 lib/convenient_service/service/plugins/has_j_send_result_params_validations/using_dry_validation/middleware.rb