links_controller.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # frozen_string_literal: true
  2. class Api::V1::Trends::LinksController < Api::BaseController
  3. before_action :set_links
  4. after_action :insert_pagination_headers
  5. DEFAULT_LINKS_LIMIT = 10
  6. def index
  7. render json: @links, each_serializer: REST::Trends::LinkSerializer
  8. end
  9. private
  10. def enabled?
  11. Setting.trends
  12. end
  13. def set_links
  14. @links = begin
  15. if enabled?
  16. links_from_trends.offset(offset_param).limit(limit_param(DEFAULT_LINKS_LIMIT))
  17. else
  18. []
  19. end
  20. end
  21. end
  22. def links_from_trends
  23. scope = Trends.links.query.allowed.in_locale(content_locale)
  24. scope = scope.filtered_for(current_account) if user_signed_in?
  25. scope
  26. end
  27. def insert_pagination_headers
  28. set_pagination_headers(next_path, prev_path)
  29. end
  30. def pagination_params(core_params)
  31. params.slice(:limit).permit(:limit).merge(core_params)
  32. end
  33. def next_path
  34. api_v1_trends_links_url pagination_params(offset: offset_param + limit_param(DEFAULT_LINKS_LIMIT)) if records_continue?
  35. end
  36. def prev_path
  37. api_v1_trends_links_url pagination_params(offset: offset_param - limit_param(DEFAULT_LINKS_LIMIT)) if offset_param > limit_param(DEFAULT_LINKS_LIMIT)
  38. end
  39. def records_continue?
  40. @links.size == limit_param(DEFAULT_LINKS_LIMIT)
  41. end
  42. def offset_param
  43. params[:offset].to_i
  44. end
  45. end