Mock api - My first example sort and paginate

schema "users"

# generating dynamic dataset
total_items = 32
all_items = generate total_items

# page_size and last_page
page_size = (10).to_f
if(params.key?('page_size'))
  page_size = params['page_size'].to_f
end
last_page = (total_items/page_size).ceil()

# page
page = 1
if(params.key?('page'))
  page = params['page'].to_i
end

# order_by
order_by = 'id'
if(params.key?('order_by'))
  order_by = params['order_by']
end  

# order asc|desc
order = 'asc'
all_items = all_items.sort_by { |elem| elem[order_by]}
if(params.key?('order'))
  if params['order'] == 'desc'   
    all_items = all_items.reverse
    order = 'desc'
  end
end

min_index = (page * page_size) - page_size
max_index = (page * page_size)

# forzamos max_index para que el máximo index
# no sobrepase total_items
if max_index > total_items
  	max_index = total_items
end  

items = []
while (min_index < max_index)
  items.push(all_items[min_index])     
  min_index = min_index + 1
end

if (page > last_page)
  # Override the default response status (200)
  status 400
  # Return a JSON object with an error message
  { 
    "code": 400,
    "error": "Bad Request",
    "message": "page param, must be less than or equal to last_page (max allowed is: ?page=" + last_page.to_s + ")"
  }
else  
  {
    "pagination": {
      "page": page,  
      "page_size": page_size,
      "last_page": last_page, 
      "total_items": total_items
    },
    "order":{
      "order_by": order_by,
      "order": order
    },
    "items": items  
  }
end