Skip to content

Commit

Permalink
add offset and limit support to controller index action
Browse files Browse the repository at this point in the history
  • Loading branch information
classicalliu committed Jul 12, 2018
1 parent bdc2d8e commit ad04b1c
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions app/controllers/api/blocks_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ class Api::BlocksController < ApplicationController
# "transactionTo": "max transaction count", // integer
# "page": "1", // default 1
# "perPage": "10", // default 10
#
# # offset and limit has lower priority than page and perPage
# "offset": "1", // database offset for pagination
# "limit": "10", //database limit for pagination
# }
# GET /api/blocks
def index
Expand All @@ -17,10 +21,20 @@ def index
transaction_count_lteq: parse_hex(params[:transactionTo])
}

blocks = Block.ransack(options).result.order(block_number: :desc).page(params[:page]).per(params[:perPage])
blocks = Block.ransack(options).result.order(block_number: :desc)

if params[:page].nil? && !params[:offset].nil?
# use offset and limit
total_count = blocks.count
blocks = blocks.offset(params[:offset]).limit(params[:limit])
else
# use page and perPage
blocks = blocks.page(params[:page]).per(params[:perPage])
total_count = blocks.total_count
end

render json: {
count: blocks.total_count,
count: total_count,
blocks: ActiveModelSerializers::SerializableResource.new(blocks, each_serializer: ::Api::BlockSerializer)
}
end
Expand Down

0 comments on commit ad04b1c

Please sign in to comment.