docbrown/app/controllers/api/v1/reactions_controller.rb
Joshua Wehner 2ff67bda24
Try an idempotentish reaction create API (#18377)
* Try an idempotentish reaction create API

* Add tests for create API endpoint

* Try -> ReactionHandler

* Fix existing tests first

* Tests for .toggle; fix broken handle_existing

* Use the Handler

* Tweak http status for reaction create

* Use the category reader

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>
2022-08-30 16:43:18 +02:00

53 lines
1.6 KiB
Ruby

module Api
module V1
class ReactionsController < ApiController
before_action :authenticate!
def create
remove_count_cache_key
result = ReactionHandler.create(params, current_user: current_user || @user)
if result.success?
render json: {
result: result.action,
category: result.category,
id: result.reaction.id,
reactable_id: result.reaction.reactable_id,
reactable_type: result.reaction.reactable_type
},
status: (result.action == "create" ? :created : :ok)
else
render json: { error: result.errors_as_sentence, status: 422 }, status: :unprocessable_entity
end
end
def toggle
remove_count_cache_key
result = ReactionHandler.toggle(params, current_user: current_user || @user)
if result.success?
render json: {
result: result.action,
category: result.category,
id: result.reaction.id,
reactable_id: result.reaction.reactable_id,
reactable_type: result.reaction.reactable_type
}
else
render json: { error: result.errors_as_sentence, status: 422 }, status: :unprocessable_entity
end
end
private
# TODO: should this move to toggle service? refactor?
def remove_count_cache_key
return unless params[:reactable_type] == "Article"
Rails.cache.delete "count_for_reactable-Article-#{params[:reactable_id]}"
end
end
end
end