Sha256: 4151e56202f8272e4bf3a9bddab8e87fd3cebfd122a4b630a69e985785d45ec2

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

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

            def next(...)
              return entity.failure(data: errors) if errors.any?

              chain.next(...)
            end

            private

            ##
            # 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

            def constructor_kwargs
              @constructor_kwargs ||= entity.constructor_arguments.kwargs
            end

            def contract
              @contract ||= entity.class.contract
            end

            def resolve_errors
              return {} unless contract.schema

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
convenient_service-0.13.0 lib/convenient_service/service/plugins/has_j_send_result_params_validations/using_dry_validation/middleware.rb