From 4a273fb704db0656ea2f1d7c608d613790db72ae Mon Sep 17 00:00:00 2001 From: Martin Meyerhoff Date: Thu, 20 Jul 2023 17:16:53 +0200 Subject: [PATCH] Import fixes for pagination from jsonapi.rb PR See https://github.com/stas/jsonapi.rb/pull/91 for details on what these fix. --- .../alchemy/json_api/pages_controller.rb | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/app/controllers/alchemy/json_api/pages_controller.rb b/app/controllers/alchemy/json_api/pages_controller.rb index 2a1f169..817ed47 100644 --- a/app/controllers/alchemy/json_api/pages_controller.rb +++ b/app/controllers/alchemy/json_api/pages_controller.rb @@ -139,6 +139,42 @@ def base_page_scope def jsonapi_serializer_class(_resource, _is_collection) ::Alchemy::JsonApi::PageSerializer end + + # These overrides have to be in place until + # https://github.com/stas/jsonapi.rb/pull/91 + # is merged and released + def jsonapi_paginate(resources) + @_jsonapi_original_size = resources.size + super + end + + def jsonapi_pagination_meta(resources) + return {} unless JSONAPI::Rails.is_collection?(resources) + + _, limit, page = jsonapi_pagination_params + + numbers = { current: page } + + total = @_jsonapi_original_size + + last_page = [1, (total.to_f / limit).ceil].max + + if page > 1 + numbers[:first] = 1 + numbers[:prev] = page - 1 + end + + if page < last_page + numbers[:next] = page + 1 + numbers[:last] = last_page + end + + if total.present? + numbers[:records] = total + end + + numbers + end end end end