summaryrefslogtreecommitdiff
path: root/app/controllers/api/carts_controller.rb
blob: d7c1529d950eac8320a458eb50260a585cc262e7 (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
# frozen_string_literal: true

module Api
  # CartsController
  class CartsController < AuthenticatedController
    append_before_action :initialize_cart

    def show
      render json: serialized_object.serializable_hash, status: :ok
    end

    def create
      product_cart = @cart.add_product(permitted_params[:product_id], permitted_params[:quantity])

      if product_cart.errors.empty?
        render json: serialized_object.serializable_hash, status: :ok
      else
        render json: { errors: product_cart.errors.as_json }, status: :unprocessable_entity
      end
    end

    def destroy
      if @cart.delete_product(params[:id])
        render status: :no_content
      else
        render status: :not_found
      end
    end

    private

    def serialized_object
      CartSerializer.new(@cart)
    end

    def permitted_params
      params.permit(:product_id, :quantity)
    end

    def initialize_cart
      @cart = current_user_account.cart
    end
  end
end