Understanding Pagination

Understanding the Problem

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:

Devising a Plan

  1. Parse and validate query parameters
  2. Set default values if parameters are missing
  3. Convert page/size into limit/offset
  4. Handle error cases
  5. Modify the database query
  6. Return paginated results

Implementation

Let's break this down into manageable pieces:

Basic Implementation (routes/api/students.js)

// 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
    });
});
    

Real World Examples

Pagination is everywhere in our daily digital interactions:

Understanding Limit and Offset

Think of pagination like serving food at a buffet:

Formula Breakdown

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)
    

Error Handling

Common errors to check for:

Testing the Solution

Test cases should include:

Performance Considerations

Pagination helps with:

Advanced Topics

Once you master basic pagination, consider exploring: