1
0

markers_controller.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. @markers = current_user.markers.where(timeline: Array(params[:timeline])).index_by(&:timeline)
  8. render json: serialize_map(@markers)
  9. end
  10. def create
  11. Marker.transaction do
  12. @markers = {}
  13. resource_params.each_pair do |timeline, timeline_params|
  14. @markers[timeline] = current_user.markers.find_or_initialize_by(timeline: timeline)
  15. @markers[timeline].update!(timeline_params)
  16. end
  17. end
  18. render json: serialize_map(@markers)
  19. rescue ActiveRecord::StaleObjectError
  20. render json: { error: 'Conflict during update, please try again' }, status: 409
  21. end
  22. private
  23. def serialize_map(map)
  24. serialized = {}
  25. map.each_pair do |key, value|
  26. serialized[key] = ActiveModelSerializers::SerializableResource.new(value, serializer: REST::MarkerSerializer).as_json
  27. end
  28. Oj.dump(serialized)
  29. end
  30. def resource_params
  31. params.slice(*Marker::TIMELINES).permit(*Marker::TIMELINES.map { |timeline| { timeline.to_sym => [:last_read_id] } })
  32. end
  33. end