accounts_controller.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # frozen_string_literal: true
  2. class Api::V1::Lists::AccountsController < Api::BaseController
  3. before_action -> { doorkeeper_authorize! :read, :'read:lists' }, only: [:show]
  4. before_action -> { doorkeeper_authorize! :write, :'write:lists' }, except: [:show]
  5. before_action :require_user!
  6. before_action :set_list
  7. after_action :insert_pagination_headers, only: :show
  8. def show
  9. @accounts = load_accounts
  10. render json: @accounts, each_serializer: REST::AccountSerializer
  11. end
  12. def create
  13. ApplicationRecord.transaction do
  14. list_accounts.each do |account|
  15. @list.accounts << account
  16. end
  17. end
  18. render_empty
  19. end
  20. def destroy
  21. ListAccount.where(list: @list, account_id: account_ids).destroy_all
  22. render_empty
  23. end
  24. private
  25. def set_list
  26. @list = List.where(account: current_account).find(params[:list_id])
  27. end
  28. def load_accounts
  29. if unlimited?
  30. @list.accounts.without_suspended.includes(:account_stat).all
  31. else
  32. @list.accounts.without_suspended.includes(:account_stat).paginate_by_max_id(limit_param(DEFAULT_ACCOUNTS_LIMIT), params[:max_id], params[:since_id])
  33. end
  34. end
  35. def list_accounts
  36. Account.find(account_ids)
  37. end
  38. def account_ids
  39. Array(resource_params[:account_ids])
  40. end
  41. def resource_params
  42. params.permit(account_ids: [])
  43. end
  44. def insert_pagination_headers
  45. set_pagination_headers(next_path, prev_path)
  46. end
  47. def next_path
  48. return if unlimited?
  49. if records_continue?
  50. api_v1_list_accounts_url pagination_params(max_id: pagination_max_id)
  51. end
  52. end
  53. def prev_path
  54. return if unlimited?
  55. unless @accounts.empty?
  56. api_v1_list_accounts_url pagination_params(since_id: pagination_since_id)
  57. end
  58. end
  59. def pagination_max_id
  60. @accounts.last.id
  61. end
  62. def pagination_since_id
  63. @accounts.first.id
  64. end
  65. def records_continue?
  66. @accounts.size == limit_param(DEFAULT_ACCOUNTS_LIMIT)
  67. end
  68. def pagination_params(core_params)
  69. params.slice(:limit).permit(:limit).merge(core_params)
  70. end
  71. def unlimited?
  72. params[:limit] == '0'
  73. end
  74. end