# frozen_string_literal: true module ErpIntegration module Fulfil module PaginationMethods DEFAULT_LIMIT = 500 # Default limit set in FF DEFAULT_OFFSET = 0 # Default offset set by FF MAX_LIMIT = 500 # Max limit set by FF attr_accessor :limit_value, :offset_value, :page_number # The {#offset} method allows navigating through the returned resources from # Fulfil's API endpoints just as with a regular database. # # @param value [String, Integer] The offset for the number of resources. # @return [ErpIntegration::Fulfil::ApiResource] def offset(value) clone.offset!(value.to_i) end def offset!(value) self.offset_value = value self end # By default, Fulfil returns the first 500 records for every query to their # API endpoints. With the {#limit} method, it's possible to modify the number # of records to return. # # NOTE: The maximum limit is 500 per dictation of Fulfil. # # @param value [String, Integer] The number of resources to return. # @return [ErpIntegration::Fulfil::ApiResource] def limit(value) clone.limit!(value.to_i) end def limit!(value) self.limit_value = [value, MAX_LIMIT].min self end alias per_page limit # The `page` method will simplify the use of `limit` and `offset` together with # the `per_page` method. Is the quantity of pages that we want to get on the response. # It sets the instance variable page_number which will be useful to calculate the offset # lazily when the method `calculated_offset` is called. This is because we need to know # first the limit before calculate the offset # # @param page_number [Integer, String] # @return [ErpIntegration::Fulfil::ApiResource] def page(page_number) clone.page!(page_number.to_i) end # @param page_number [Integer] # @return [ErpIntegration::Fulfil::ApiResource] def page!(page_number) self.page_number = page_number self end private # @return [Boolean] def paginating? !page_number.nil? end # The `calculated_offset` will calculate the offset_value instance variable lazily # @return [Integer] def calculated_offset return offset_value unless paginating? # When paginating we want to set the {#limit_value} to equal the {MAX_LIMIT} # when the {#limit_value} isn't set to prevent inconsistencies in the API response. limit!(MAX_LIMIT) if limit_value.nil? # Now, calculate the offset_value based on the {#limit_value} and the {#page_number}. offset!((page_number - 1) * limit_value) offset_value end end end end