markers_controller.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # frozen_string_literal: true
  2. class Api::V1::MarkersController < Api::BaseController
  3. before_action -> { doorkeeper_authorize! :read, :'read:statuses' }, only: [:index]
  4. before_action -> { doorkeeper_authorize! :write, :'write:statuses' }, except: [:index]
  5. before_action :require_user!
  6. def index
  7. with_read_replica do
  8. @markers = current_user.markers.where(timeline: Array(params[:timeline])).index_by(&:timeline)
  9. end
  10. render json: serialize_map(@markers)
  11. end
  12. def create
  13. Marker.transaction do
  14. @markers = {}
  15. resource_params.each_pair do |timeline, timeline_params|
  16. @markers[timeline] = current_user.markers.find_or_initialize_by(timeline: timeline)
  17. @markers[timeline].update!(timeline_params)
  18. end
  19. end
  20. render json: serialize_map(@markers)
  21. rescue ActiveRecord::StaleObjectError
  22. render json: { error: 'Conflict during update, please try again' }, status: 409
  23. end
  24. private
  25. def serialize_map(map)
  26. serialized = {}
  27. map.each_pair do |key, value|
  28. serialized[key] = ActiveModelSerializers::SerializableResource.new(value, serializer: REST::MarkerSerializer).as_json
  29. end
  30. Oj.dump(serialized)
  31. end
  32. def resource_params
  33. params.slice(*Marker::TIMELINES).permit(*Marker::TIMELINES.map { |timeline| { timeline.to_sym => [:last_read_id] } })
  34. end
  35. end