Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 30 additions & 21 deletions JsonApiToolkit/Controllers/JsonApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -206,25 +206,7 @@ string resourceType
int totalCount = await filteredQuery.CountAsync().ConfigureAwait(false);
LogCountResults<T>(parameters, totalCount);

if (Options.StrictPagination && parameters.Pagination != null && totalCount > 0)
{
int totalPages = (int)Math.Ceiling(totalCount / (double)parameters.Pagination.Size);
if (parameters.Pagination.Number > totalPages)
{
throw new JsonApiNotFoundException(
$"Page {parameters.Pagination.Number} does not exist. "
+ $"This collection has {totalPages} page(s). Request a page between 1 and {totalPages}.",
JsonApiErrorCodes.InvalidPageNumber,
new ErrorSource { Parameter = "page[number]" },
new Dictionary<string, object>
{
["value"] = parameters.Pagination.Number,
["totalPages"] = totalPages,
["totalResources"] = totalCount,
}
);
}
}
EnforceStrictPagination(Options, parameters, totalCount);

if (parameters.Pagination != null)
filteredQuery = filteredQuery.ApplyPagination(parameters.Pagination, totalCount);
Expand All @@ -241,7 +223,7 @@ string resourceType
parameters.Pagination?.Size ?? totalCount
);

IActionResult? projectionResult = await TryApplyDatabaseProjection(
IActionResult? projectionResult = await TryApplyDatabaseProjectionAsync(
filteredQuery,
resourceType,
baseUrl,
Expand Down Expand Up @@ -511,6 +493,33 @@ List<string> mappedIncludes
return filteredQuery;
}

private static void EnforceStrictPagination(
JsonApiOptions options,
QueryParameters parameters,
int totalCount
)
{
if (!options.StrictPagination || parameters.Pagination is null || totalCount == 0)
return;

int totalPages = (int)Math.Ceiling(totalCount / (double)parameters.Pagination.Size);
if (parameters.Pagination.Number <= totalPages)
return;

throw new JsonApiNotFoundException(
$"Page {parameters.Pagination.Number} does not exist. "
+ $"This collection has {totalPages} page(s). Request a page between 1 and {totalPages}.",
JsonApiErrorCodes.InvalidPageNumber,
new ErrorSource { Parameter = "page[number]" },
new Dictionary<string, object>
{
["value"] = parameters.Pagination.Number,
["totalPages"] = totalPages,
["totalResources"] = totalCount,
}
);
}

private void LogCountResults<T>(QueryParameters parameters, int totalCount)
{
if (totalCount == 0 && parameters.Filter?.Filters?.Count > 0)
Expand All @@ -526,7 +535,7 @@ private void LogCountResults<T>(QueryParameters parameters, int totalCount)
}
}

private async Task<IActionResult?> TryApplyDatabaseProjection<T>(
private async Task<IActionResult?> TryApplyDatabaseProjectionAsync<T>(
IQueryable<T> filteredQuery,
string resourceType,
string baseUrl,
Expand Down
Loading