links_controller.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # frozen_string_literal: true
  2. class Api::V1::Trends::LinksController < Api::BaseController
  3. vary_by 'Authorization, Accept-Language'
  4. before_action :set_links
  5. after_action :insert_pagination_headers
  6. DEFAULT_LINKS_LIMIT = 10
  7. def index
  8. cache_if_unauthenticated!
  9. render json: @links, each_serializer: REST::Trends::LinkSerializer
  10. end
  11. private
  12. def enabled?
  13. Setting.trends
  14. end
  15. def set_links
  16. @links = if enabled?
  17. links_from_trends.offset(offset_param).limit(limit_param(DEFAULT_LINKS_LIMIT))
  18. else
  19. []
  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