File size: 1,882 Bytes
5010ad7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | module Api
module V1
class BaseController < ActionController::API
include Pundit::Authorization
before_action :authenticate_api_user!
before_action :set_locale
rescue_from Pundit::NotAuthorizedError do
render json: { error: "Forbidden" }, status: :forbidden
end
rescue_from ActiveRecord::RecordNotFound do
render json: { error: "Not Found" }, status: :not_found
end
rescue_from ActiveRecord::RecordInvalid do |e|
render json: { errors: e.record.errors.full_messages }, status: :unprocessable_entity
end
private
def authenticate_api_user!
# Devise JWT handles authentication via Warden
authenticate_user! unless action_allows_anonymous?
end
def action_allows_anonymous?
false # Override in controllers that allow public access
end
def set_locale
locale = request.headers["Accept-Language"] || params[:locale] || "en"
I18n.locale = I18n.available_locales.include?(locale.to_sym) ? locale : :en
end
def pagy(collection, vars = {})
page = params[:page].to_i || 1
items = vars[:items] || 20
page = 1 if page < 1
offset = (page - 1) * items
pagy_obj = OpenStruct.new(
page: page,
items: items,
offset: offset,
count: collection.count,
pages: (collection.count.to_f / items).ceil,
next: (page * items < collection.count) ? page + 1 : nil,
prev: page > 1 ? page - 1 : nil
)
[ pagy_obj, collection.offset(offset).limit(items) ]
end
def pagy_metadata(pagy)
{
count: pagy.count,
page: pagy.page,
items: pagy.items,
pages: pagy.pages,
next: pagy.next,
prev: pagy.prev
}
end
end
end
end
|