Sha256: 66302a89ecfcaf2289afbadcf905b87b9454753e8975a9556568a5fc719dd2c7

Contents?: true

Size: 1.72 KB

Versions: 3

Compression:

Stored size: 1.72 KB

Contents

# typed: strict
# frozen_string_literal: true

require 'clean_architecture/entities/failure_details'
require 'clean_architecture/matchers/use_case_result'
require 'clean_architecture/queries/http_failure_code'
require 'clean_architecture/queries/http_success_code'
require 'sorbet-runtime'

module CleanArchitecture
  module Serializers
    class JsonResponseFromResult
      extend T::Sig

      sig { params(result: Dry::Monads::Result, http_method: String, success_payload_proc: T.proc.params(success_value: T.untyped).returns(T::Hash[T.untyped, T.untyped])).void }
      def initialize(result, http_method, success_payload_proc)
        @result = T.let(result, Dry::Monads::Result)
        @http_method = T.let(http_method, String)
        @success_payload_proc = T.let(success_payload_proc, T.proc.params(success_value: T.untyped).returns(T::Hash[T.untyped, T.untyped]))
      end

      sig { returns(T::Hash[Symbol, T.untyped]) }
      def to_h
        {
          status: http_status_code,
          json: json
        }
      end

      private

      sig { returns(Symbol) }
      def http_status_code
        Matchers::UseCaseResult.call(@result) do |matcher|
          matcher.success { Queries::HttpSuccessCode.new(@http_method).to_sym }
          matcher.failure do |failure_value|
            Queries::HttpFailureCode.new(failure_value.type).to_sym
          end
        end
      end

      sig { returns(T::Hash[Symbol, T.untyped]) }
      def json
        Matchers::UseCaseResult.call(@result) do |matcher|
          matcher.success { |value| { data: @success_payload_proc.call(value) } }
          matcher.failure do |failure_details|
            { errors: [failure_details.message] }
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
clean-architecture-5.0.2 lib/clean_architecture/serializers/json_response_from_result.rb
clean-architecture-5.0.1 lib/clean_architecture/serializers/json_response_from_result.rb
clean-architecture-4.0.1 lib/clean_architecture/serializers/json_response_from_result.rb