summaryrefslogtreecommitdiff
path: root/app/controllers/api/addresses_controller.rb
blob: 834f721f29c81b21e918ca3a1fbcf4eff295eb70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# frozen_string_literal: true

module Api
  # AddressesController
  class AddressesController < AuthenticatedController
    def index
      @addresses = current_user_account.addresses

      render json: serialized_collection.serializable_hash, status: :ok
    end

    def show
      @address = current_user_account.addresses.find_by(id: params[:id])

      if @address.nil?
        render status: :not_found
      else
        render json: serialized_object.serializable_hash, status: :ok
      end
    end

    def create
      @service = Addresses::CreateAddressService.new(current_user_account, service_params)

      begin
        unless @service.call
          render json: { errors: @service.error_messages }, status: :unprocessable_entity
          return
        end
      rescue ActiveRecord::RecordNotUnique
        render json: { error_message: 'Ya cuenta con esta dirección' }, status: :unprocessable_entity
        return
      end

      @address = @service.address
      render json: serialized_object.serializable_hash, status: :ok
    end

    def update
      @service = Addresses::UpdateAddressService.new(current_user_account, params[:id], service_params)

      begin
        case @service.call
        when :not_found
          render status: :not_found
        when :unprocessable_entity
          render json: { errors: @service.error_messages }, status: :unprocessable_entity
        else
          @address = @service.address
          render json: serialized_object.serializable_hash, status: :ok
        end
      rescue ActiveRecord::RecordNotUnique
        @address = current_user_account.addresses.find(params[:id])
        render json: serialized_object.serializable_hash, status: :ok
      end
    end

    def destroy
      @address = current_user_account.addresses.find_by(id: params[:id])

      render status: :not_found and return if @address.nil?

      Addresses::DestroyAddressService.new(current_user_account, params, @address).call
      render status: :no_content
    end

    private

    def serialized_object
      AddressSerializer.new(@address)
    end

    def serialized_collection
      AddressSerializer.new(@addresses.page(params[:page]))
    end

    def service_params
      params.permit(:number, :street, :zip_code, :country, :city)
    end
  end
end