Skip to content

Instantly share code, notes, and snippets.

@pablorcruh
Last active January 24, 2025 18:54
Show Gist options
  • Save pablorcruh/822da803d41d969f6a4e642c322bacaa to your computer and use it in GitHub Desktop.
Save pablorcruh/822da803d41d969f6a4e642c322bacaa to your computer and use it in GitHub Desktop.
Posible Interceptor con repositorio
@Component
public class PaginationInterceptor implements HandlerInterceptor {
@Autowired
private PaginationService paginationService;
@Autowired
private ProductRepository productRepository;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) {
// Read pagination parameters
int currentIndex = Integer.parseInt(
request.getHeader("X-Current-Index") != null
? request.getHeader("X-Current-Index")
: "0"
);
int itemsPerPage = Integer.parseInt(
request.getHeader("X-Items-Per-Page") != null
? request.getHeader("X-Items-Per-Page")
: String.valueOf(paginationService.getDefaultItemsPerPage())
);
// Ensure items per page doesn't exceed maximum
itemsPerPage = Math.min(itemsPerPage, paginationService.getMaxItemsPerPage());
// Get total items from repository
int totalItems = productRepository.getTotalProducts();
// Calculate total pages
int totalPages = paginationService.calculateTotalPages(totalItems, itemsPerPage);
int currentPage = (currentIndex / itemsPerPage) + 1;
// Inject headers
response.addHeader("X-Current-Index", String.valueOf(currentIndex));
response.addHeader("X-Items-Per-Page", String.valueOf(itemsPerPage));
response.addHeader("X-Current-Page", String.valueOf(currentPage));
response.addHeader("X-Total-Items", String.valueOf(totalItems));
response.addHeader("X-Total-Pages", String.valueOf(totalPages));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment