Thursday 15 October 2015

WebAPI Data call with Pagination

Most of the time when we are calling for a data API call, we fetch all records and do the pagination in the client side. But this hinders the network performance and lead to a heavy unnecessary data fetch. Hence , it is better to do the pagination in the server side and return only required data to the client.

Following code demonstrates an easy way to achieve this.

1. The WebAPI controller code
 
[HttpGet, Route("ByClient/{clientID:int}")]
public IHttpActionResult GetByClient(int clientID, int pageSize=5, int page=1 ,string sort= "id")
{
      try
      {
          object header;
          var receivedModel = VehicleProvider.GetByClient(clientID, pageSize , page,  sort, out header);

          HttpContext.Current.Response.Headers.Add("Pagination",
              Newtonsoft.Json.JsonConvert.SerializeObject(header));

          IHttpActionResult response = Ok(receivedModel);
          return response;
     }
     catch (Exception)
     {
          return InternalServerError();
     }
           
}

The actual pagination is going inside the BL's GetByClient method. In this code we are adding a response header attribute as "Pagination". This information is useful to client in order to determine the current data location and the total size.
2. The BL Code
 
public IQueryable GetByClient(int clientID, int pageSize, int page, string sort, out object header)
        {
            var totalCount = _vehicleService.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);


            var paginationHeader = new
            {
                currentPage = page,
                pageSize = pageSize,
                totalCount = totalCount,
                totalPages = totalPages
            };

            header = paginationHeader;

            var results = VehicleMap.EntityToModelQueryble( _vehicleService.GetAll(r => r.ClientId == clientID));
            return results.ApplySort(sort).Skip(pageSize*(page - 1))
                .Take(pageSize);
        }

In this code , we are creating a new object to pass as the header.

No comments:

Post a Comment