← Alle AufgabenNode.js · Junior

Paginierung aus Query-Parametern

Eine API bekommt ?page=2&limit=10, also Strings. Schreib paginate(items, query), das { data, page, limit, total, totalPages } liefert.

Die Standardwerte sind page = 1 und limit = 10. Ein ungültiger Wert (keine ganze Zahl, kleiner als 1, keine Zahl) wird durch den Standard ersetzt, und limit ist auf 100 begrenzt, damit ein Client nicht die ganze Tabelle auf einmal holen kann. Eine Seite jenseits der Daten ergibt ein leeres data.

Tests (6)

  1. const items = Array.from({ length: 25 }, (_, i) => i + 1);
    expect(paginate(items, { page: '2', limit: '10' })).toEqual({ data: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], page: 2, limit: 10, total: 25, totalPages: 3 });
  2. const items = Array.from({ length: 25 }, (_, i) => i + 1);
    expect(paginate(items, { page: '3', limit: '10' }).data).toEqual([21, 22, 23, 24, 25]);
  3. const items = [1, 2, 3];
    expect(paginate(items, {})).toEqual({ data: [1, 2, 3], page: 1, limit: 10, total: 3, totalPages: 1 });
  4. const items = [1, 2, 3];
    expect(paginate(items, { page: 'abc', limit: '-5' })).toEqual({ data: [1, 2, 3], page: 1, limit: 10, total: 3, totalPages: 1 });
    expect(paginate(items, { page: '1.5' }).page).toBe(1);
  5. const items = Array.from({ length: 500 }, (_, i) => i);
    const result = paginate(items, { limit: '1000' });
    expect(result.limit).toBe(100);
    expect(result.data).toHaveLength(100);
  6. const result = paginate([1, 2], { page: '5', limit: '10' });
    expect(result.data).toEqual([]);
    expect(result.totalPages).toBe(1);
    expect(paginate([], {}).totalPages).toBe(0);