Imagine you're reading a very long book. Instead of showing all pages at once, the book is divided into manageable chunks. This is exactly what pagination does for our data! We need to:
Let's break this down into manageable pieces:
// GET /students
router.get('/', async (req, res) => {
// Step 1: Parse query parameters
let page = parseInt(req.query.page) || 1; // Default to page 1
let size = parseInt(req.query.size) || 10; // Default to 10 items per page
// Step 2: Initialize error result object
const errorResult = {
errors: [],
count: 0,
pageCount: 0
};
// Step 3: Validate parameters
if (page < 0 || size < 0 || size > 200) {
errorResult.errors.push({
message: 'Requires valid page and size params'
});
return res.status(400).json(errorResult);
}
// Step 4: Special case for developers
if (page === 0 && size === 0) {
// Return all results without pagination
const students = await Student.findAll();
return res.json({
rows: students,
page: 1
});
}
// Step 5: Calculate limit and offset
const limit = size;
const offset = (page - 1) * size;
// Step 6: Execute query with pagination
const result = await Student.findAll({
limit,
offset
});
// Step 7: Return paginated results
res.json({
rows: result,
page
});
});
Pagination is everywhere in our daily digital interactions:
Think of pagination like serving food at a buffet:
offset = (page - 1) * size
// Example:
// Page 1, Size 10: offset = (1-1) * 10 = 0 (Start at beginning)
// Page 2, Size 10: offset = (2-1) * 10 = 10 (Skip first 10 items)
// Page 3, Size 10: offset = (3-1) * 10 = 20 (Skip first 20 items)
Common errors to check for:
Test cases should include:
Pagination helps with:
Once you master basic pagination, consider exploring: