Skip to content

Commit

Permalink
Add total item count header to paged responses.
Browse files Browse the repository at this point in the history
  • Loading branch information
ledsoft committed Apr 23, 2024
1 parent d164a28 commit b424fa2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ public void onApplicationEvent(PaginatedResultRetrievedEvent event) {
if (header.hasLinks()) {
event.getResponse().addHeader(HttpHeaders.LINK, header.toString());
}
event.getResponse().addHeader(Constants.X_TOTAL_COUNT_HEADER, Long.toString(page.getTotalElements()));
}

private String generateNextPageLink(Page<?> page, UriComponentsBuilder uriBuilder) {
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/cz/cvut/kbss/study/util/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,10 @@ private Constants() {
* Name of the request parameter specifying sorting.
*/
public static final String SORT_PARAM = "sort";

/**
* Represents the X-Total-Count HTTP header used to convey the total number of items in paged or otherwise
* restricted response.
*/
public static final String X_TOTAL_COUNT_HEADER = "X-Total-Count";
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

Expand Down Expand Up @@ -182,4 +183,13 @@ public void generatesFirstAndLastLinksForOnlyPage() {
assertThat(lastLink, containsString(pageSize(size)));
}

@Test
public void generatesTotalCountHeader() {
final int size = records.size();
final Page<PatientRecordDto> page = new PageImpl<>(records, PageRequest.of(0, size / 2), records.size());
listener.onApplicationEvent(event(page));
final String totalCountHeader = responseMock.getHeader(Constants.X_TOTAL_COUNT_HEADER);
assertNotNull(totalCountHeader);
assertEquals(size, Integer.parseInt(totalCountHeader));
}
}

0 comments on commit b424fa2

Please sign in to comment.