demarches-normaliennes/app/controllers/api/v1/dossiers_controller.rb

60 lines
1.5 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2016-01-20 15:48:46 +01:00
class API::V1::DossiersController < APIController
2023-09-20 09:30:14 +02:00
before_action :check_api_token
before_action :fetch_dossiers
DEFAULT_PAGE_SIZE = 100
MAX_PAGE_SIZE = 1000
2019-06-20 12:11:39 +02:00
ORDER_DIRECTIONS = { 'asc' => :asc, 'desc' => :desc }
2016-01-20 15:48:46 +01:00
def index
2018-11-01 14:04:32 +01:00
dossiers = @dossiers.page(params[:page]).per(per_page)
2016-11-15 09:54:17 +01:00
2023-09-20 09:30:14 +02:00
render json: { dossiers: dossiers.map { |dossier| DossiersSerializer.new(dossier) }, pagination: pagination(dossiers) }
2017-04-14 17:05:38 +02:00
rescue ActiveRecord::RecordNotFound
2023-09-20 09:30:14 +02:00
render json: {}, status: :not_found
2016-01-20 15:48:46 +01:00
end
def show
2018-11-01 14:04:32 +01:00
dossier = @dossiers.for_api.find(params[:id])
DossierPreloader.load_one(dossier)
2016-11-15 09:54:17 +01:00
2023-09-20 09:30:14 +02:00
render json: { dossier: DossierSerializer.new(dossier).as_json }
2017-04-14 17:05:38 +02:00
rescue ActiveRecord::RecordNotFound
2023-09-20 09:30:14 +02:00
render json: {}, status: :not_found
end
private
def pagination(dossiers)
2016-01-20 15:48:46 +01:00
{
2018-01-15 19:02:12 +01:00
page: dossiers.current_page,
resultats_par_page: dossiers.limit_value,
nombre_de_page: dossiers.total_pages
2016-01-20 15:48:46 +01:00
}
end
2017-12-28 19:31:28 +01:00
def per_page # inherited value from will_paginate
resultats_par_page = params[:resultats_par_page]&.to_i
if resultats_par_page && resultats_par_page > 0
[resultats_par_page, MAX_PAGE_SIZE].min
else
DEFAULT_PAGE_SIZE
end
2017-12-28 19:31:28 +01:00
end
2023-09-20 09:30:14 +02:00
def fetch_dossiers
procedure = @api_token.procedures.find(params[:procedure_id])
2023-09-20 09:30:14 +02:00
order = ORDER_DIRECTIONS.fetch(params[:order], :asc)
@dossiers = procedure
.dossiers
.visible_by_administration
.order_by_created_at(order)
2018-11-01 14:04:32 +01:00
rescue ActiveRecord::RecordNotFound
render json: {}, status: :not_found
end
2017-04-04 15:27:04 +02:00
end