links_controller.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. Trends.links.query.allowed.in_locale(content_locale)
  24. end
  25. def insert_pagination_headers
  26. set_pagination_headers(next_path, prev_path)
  27. end
  28. def pagination_params(core_params)
  29. params.slice(:limit).permit(:limit).merge(core_params)
  30. end
  31. def next_path
  32. api_v1_trends_links_url pagination_params(offset: offset_param + limit_param(DEFAULT_LINKS_LIMIT)) if records_continue?
  33. end
  34. def prev_path
  35. api_v1_trends_links_url pagination_params(offset: offset_param - limit_param(DEFAULT_LINKS_LIMIT)) if offset_param > limit_param(DEFAULT_LINKS_LIMIT)
  36. end
  37. def records_continue?
  38. @links.size == limit_param(DEFAULT_LINKS_LIMIT)
  39. end
  40. def offset_param
  41. params[:offset].to_i
  42. end
  43. end