diff --git a/app/controllers/api/v1/favorites_controller.rb b/app/controllers/api/v1/favorites_controller.rb new file mode 100644 index 0000000..c615cf3 --- /dev/null +++ b/app/controllers/api/v1/favorites_controller.rb @@ -0,0 +1,42 @@ +class Api::V1::FavoritesController < Api::V1::ApiController + before_action :set_party, only: ['create'] + + def create + party_id = favorite_params[:party_id] + party = Party.find(party_id) + + if !current_user + raise Api::V1::UnauthorizedError + elsif party.user && current_user.id == party.user.id + raise Api::V1::SameFavoriteUserError + elsif Favorite.where(user_id: current_user.id, party_id: party_id).length > 0 + raise Api::V1::FavoriteAlreadyExistsError + else + ap "Create a new favorite" + object = { + user_id: current_user.id, + party_id: favorite_params[:party_id] + } + + @favorite = Favorite.new(object) + render :show, status: :created if @favorite.save! + end + end + + def destroy + raise Api::V1::UnauthorizedError unless current_user + + @favorite = Favorite.where(user_id: current_user.id, party_id: favorite_params[:party_id]).first + render :destroyed, status: :ok if @favorite && Favorite.destroy(@favorite.id) + end + + private + + def set_party + @party = Party.where("id = ?", params[:party_id]).first + end + + def favorite_params + params.require(:favorite).permit(:id, :party_id) + end +end \ No newline at end of file diff --git a/app/views/api/v1/favorites/base.json.rabl b/app/views/api/v1/favorites/base.json.rabl new file mode 100644 index 0000000..e7525b8 --- /dev/null +++ b/app/views/api/v1/favorites/base.json.rabl @@ -0,0 +1,3 @@ +object :favorite + +attributes :id, :user_id, :party_id, :created_at, :updated_at diff --git a/app/views/api/v1/favorites/destroyed.json.rabl b/app/views/api/v1/favorites/destroyed.json.rabl new file mode 100644 index 0000000..f791b2f --- /dev/null +++ b/app/views/api/v1/favorites/destroyed.json.rabl @@ -0,0 +1,5 @@ +object false + +node :destroyed do + true +end \ No newline at end of file diff --git a/app/views/api/v1/favorites/show.json.rabl b/app/views/api/v1/favorites/show.json.rabl new file mode 100644 index 0000000..2b85585 --- /dev/null +++ b/app/views/api/v1/favorites/show.json.rabl @@ -0,0 +1,3 @@ +object @favorite + +extends 'api/v1/favorites/base' \ No newline at end of file