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

module Api
  # ReviewsController
  class ReviewsController < AuthenticatedController
    skip_before_action :validate_jwt, only: :index

    def index
      @product = find_product

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

      if params[:by].present?
        render json: { posted: Reviews::HasUserAlreadyPostedReviewQuery.new(@product).review_posted?(params[:by]) },
               status: :ok
        return
      end

      @reviews = @product.product_reviews.joins(:user_account).select('product_reviews.*',
                                                                      'user_accounts.first_name as author_name')
      render json: serialized_collection.serializable_hash, status: :ok
    end

    def create
      @product = find_product

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

      @review = ProductReview.new(permitted_params.merge({ product_id: @product.id,
                                                           user_account_id: current_user_account.id }))

      if @review.save
        render json: serialized_object.serializable_hash, status: :ok
      else
        render json: { errors: @review.errors.as_json }, status: :unprocessable_entity
      end
    end

    private

    def find_product
      Product.find_by(public_id: params[:product_id])
    end

    def permitted_params
      params.permit(:review, :rating)
    end

    def serialized_collection
      @serialized_collection ||= ProductReviewSerializer.new(@reviews.page(params[:page]))
    end

    def serialized_object
      @serialized_object ||= ProductReviewSerializer.new(
        ProductReview.joins(:user_account).select('product_reviews.*',
                                                  'user_accounts.first_name as author_name')
                                          .find(@review.id)
        )
    end
  end
end