Implementing data paging 

Now, let's revise the implementation of the questions endpoint with the search query parameter so that we can use data paging:

  1. Let's start by adding a new method that will search with paging to our data repository interface:
public interface IDataRepository
{
...
IEnumerable<QuestionGetManyResponse>
GetQuestionsBySearch(string search);
IEnumerable<QuestionGetManyResponse>
GetQuestionsBySearchWithPaging(
string search,
int pageNumber,
int pageSize);

...
}

So, the method will take in the page number and size as parameters.

  1. Now, we can add the method implementation in the data repository:
public IEnumerable<QuestionGetManyResponse> 
GetQuestionsBySearchWithPaging(
string search,
int pageNumber,
int pageSize
)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
var parameters = new
{
Search = search,
PageNumber = pageNumber,
PageSize = pageSize
};
return connection.Query<QuestionGetManyResponse>(
@"EXEC dbo.Question_GetMany_BySearch_WithPaging
@Search = @Search,
@PageNumber = @PageNumber,
@PageSize = @PageSize", parameters
);
}
}

So, we are calling a stored procedure called Question_GetMany_BySearch_WithPaging to get the page of data passing in the search criteria, page number, and page size as parameters.

  1. Let's change the implementation of the GetQuestions action method in our API controller so that we can call this repository method:
[HttpGet]
public IEnumerable<QuestionGetManyResponse>
GetQuestions(
string search,
bool includeAnswers,
int page = 1,
int pageSize = 20
)
{
if (string.IsNullOrEmpty(search))
{
if (includeAnswers)
{
return _dataRepository.GetQuestionsWithAnswers();
}
else
{
return _dataRepository.GetQuestions();
}
}
else
{
return _dataRepository.GetQuestionsBySearchWithPaging(
search,
page,
pageSize
);

}
}

Notice that we also accept query parameters for the page number and page size, which are defaulted to 1 and 20, respectively.

  1. Let's start our REST API by pressing F5 in Visual Studio.
  2. Now, we can load test the current implementation using WebSurge. Let's change the request URL path to /api/questions?search=question&page=1&pagesize=20 and stick to a duration of 30 seconds with 5 threads. 
  3. Start the test. When the test has finished, we'll get our results:

We get the performance improvement we hoped for, with the endpoint now able to take 15.30 requests per second.

Data paging is well worth considering for APIs that return collections of data, particularly if the collection is large.

In the next section, we are going to tackle the subject of asynchronous code and how this can help with scalability.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.180.252