Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,31 @@ appLogger.infoSync('Quick log');
appLogger.errorSync('Error', error);
```

### Cursor-based API pagination
The app now supports cursor-based list pagination for backend endpoints such as `/courses`.

- `limit` — number of records per page
- `cursor` — opaque token returned by the previous page
- `orderBy` — stable sort field (`id`)
- `direction` — `asc` or `desc`

Response shape:

```json
{
"items": [/* Course[] */],
"nextCursor": "string | null",
"hasMore": true
}
```

Cursor format:

- URI-safe encoded JSON
- contains `{ lastId, orderBy, direction }`

Use `courseApi.getCoursesPage({ limit, cursor, orderBy, direction })` to fetch each page.

### Retrieve Logs (Development)

```typescript
Expand Down
63 changes: 63 additions & 0 deletions src/__tests__/services/api/courseApi.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import apiClient from '@/services/api/axios.config';
import { clearCache } from '@/services/api/cache';
import { courseApi } from '@/services/api/courseApi';
import { CursorPageResponse } from '@/services/api/cursorPagination';

jest.mock('@/services/api/axios.config', () => ({
__esModule: true,
default: {
get: jest.fn(),
post: jest.fn(),
put: jest.fn(),
delete: jest.fn(),
},
}));

const mockedApiClient = apiClient as jest.Mocked<typeof apiClient>;

describe('courseApi', () => {
beforeEach(() => {
jest.clearAllMocks();
clearCache();
});

it('calls the course page endpoint with cursor parameters', async () => {
const payload: CursorPageResponse<any> = {
items: [{ id: 'course-123', title: 'Course 123', description: '', instructor: { id: 'inst-1', name: 'Instructor' }, sections: [], totalLessons: 0, totalDuration: 0, level: 'beginner', category: 'general' }],
nextCursor: 'abc',
hasMore: false,
};

mockedApiClient.get.mockResolvedValueOnce({ data: payload } as any);

const result = await courseApi.getCoursesPage({ limit: 10, cursor: 'cursor-abc', orderBy: 'id', direction: 'desc' });

expect(mockedApiClient.get).toHaveBeenCalledTimes(1);
expect(mockedApiClient.get).toHaveBeenCalledWith('/courses', {
params: {
limit: 10,
cursor: 'cursor-abc',
orderBy: 'id',
direction: 'desc',
},
});
expect(result).toEqual(payload);
});

it('reuses cached page data for the same cursor request', async () => {
const payload: CursorPageResponse<any> = {
items: [{ id: 'course-456', title: 'Course 456', description: '', instructor: { id: 'inst-2', name: 'Instructor 2' }, sections: [], totalLessons: 0, totalDuration: 0, level: 'intermediate', category: 'design' }],
nextCursor: null,
hasMore: false,
};

mockedApiClient.get.mockResolvedValueOnce({ data: payload } as any);

const firstResult = await courseApi.getCoursesPage({ limit: 5, cursor: 'cursor-xyz', orderBy: 'id', direction: 'asc' });
const secondResult = await courseApi.getCoursesPage({ limit: 5, cursor: 'cursor-xyz', orderBy: 'id', direction: 'asc' });

expect(mockedApiClient.get).toHaveBeenCalledTimes(1);
expect(firstResult).toEqual(payload);
expect(secondResult).toEqual(payload);
});
});
77 changes: 77 additions & 0 deletions src/__tests__/services/api/cursorPagination.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import {
buildCursor,
CursorPageRequest,
paginateWithCursor,
parseCursor,
} from '@/services/api/cursorPagination';

describe('cursorPagination', () => {
it('encodes and decodes cursor values cleanly', () => {
const cursor = buildCursor('course-123', 'id', 'asc');
const payload = parseCursor(cursor);

expect(typeof cursor).toBe('string');
expect(payload).toEqual({ lastId: 'course-123', orderBy: 'id', direction: 'asc' });
});

it('paginates a large dataset consistently and without duplicates', () => {
const items = Array.from({ length: 100 }, (_, index) => ({
id: `course-${String(index + 1).padStart(3, '0')}`,
title: `Course ${index + 1}`,
}));

let cursor: string | undefined;
const seen = new Set<string>();
const results: string[] = [];

for (let page = 0; page < 10; page += 1) {
const request: CursorPageRequest = {
limit: 10,
cursor,
orderBy: 'id',
direction: 'asc',
};

const response = paginateWithCursor(items, request);
response.items.forEach((item) => {
expect(seen.has(item.id)).toBe(false);
seen.add(item.id);
results.push(item.id);
});

if (!response.hasMore) {
break;
}

expect(response.nextCursor).not.toBeNull();
cursor = response.nextCursor ?? undefined;
}

expect(results).toHaveLength(100);
expect(results[0]).toBe('course-001');
expect(results[results.length - 1]).toBe('course-100');
});

it('supports descending ordering and stable cursor continuation', () => {
const items = Array.from({ length: 30 }, (_, index) => ({
id: `course-${String(index + 1).padStart(3, '0')}`,
title: `Course ${index + 1}`,
}));

const firstPage = paginateWithCursor(items, { limit: 5, direction: 'desc' });

expect(firstPage.items[0].id).toBe('course-030');
expect(firstPage.hasMore).toBe(true);
expect(firstPage.nextCursor).toBeTruthy();

const secondPage = paginateWithCursor(items, {
limit: 5,
direction: 'desc',
cursor: firstPage.nextCursor ?? undefined,
});

expect(secondPage.items[0].id).toBe('course-025');
expect(secondPage.items).toHaveLength(5);
expect(secondPage.hasMore).toBe(true);
});
});
7 changes: 3 additions & 4 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ export * from './useAnalytics';
export { AuthProvider, useAuth } from './useAuth';
export * from './useBiometricAuth';
export * from './useCamera';
export * from './useCoursePagination';
export * from './useCourseProgress';
export * from './useDebounce';
export * from './useDynamicFontSize';
export * from './useFormCache';
export * from './useFormValidation';
Expand Down Expand Up @@ -33,9 +35,6 @@ export { OptimizedLongPressView, useOptimizedLongPress } from './useOptimizedLon
export { OptimizedPinchZoomView, useOptimizedPinchZoom } from './useOptimizedPinchZoom';
export { OptimizedSwipeView, useOptimizedSwipe } from './useOptimizedSwipe';
export { OptimizedVideoGesturesView, useOptimizedVideoGestures } from './useOptimizedVideoGestures';

export * from './useDebounce';
export * from './useHealthDashboard';
export * from './usePredictivePreload';
export * from './useReactProfiler';

export * from './useReactProfiler';
103 changes: 103 additions & 0 deletions src/hooks/useCoursePagination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { courseApi } from '@/services/api/courseApi';
import { CursorPageRequest } from '@/services/api/cursorPagination';
import { Course } from '@/types/course';
import { useCallback, useEffect, useState } from 'react';

export interface UseCoursePaginationOptions {
initialLimit?: number;
orderBy?: string;
direction?: 'asc' | 'desc';
}

export interface UseCoursePaginationResult {
items: Course[];
isLoading: boolean;
isRefreshing: boolean;
hasMore: boolean;
nextCursor: string | null;
loadNextPage: () => Promise<void>;
refresh: () => Promise<void>;
}

export function useCoursePagination(
options: UseCoursePaginationOptions = {},
): UseCoursePaginationResult {
const {
initialLimit = 20,
orderBy = 'id',
direction = 'asc',
} = options;

const [items, setItems] = useState<Course[]>([]);
const [nextCursor, setNextCursor] = useState<string | null>(null);
const [hasMore, setHasMore] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);

const fetchPage = useCallback(async (cursor?: string) => {
if (isLoading) {
return;
}

setIsLoading(true);

const request: CursorPageRequest = {
limit: initialLimit,
cursor,
orderBy,
direction,
};

try {
const response = await courseApi.getCoursesPage(request);

setItems((previous) => {
if (!cursor) {
return response.items;
}

const existingIds = new Set(previous.map((course) => course.id));
return [...previous, ...response.items.filter((course) => !existingIds.has(course.id))];
});
setNextCursor(response.nextCursor);
setHasMore(response.hasMore);
} finally {
setIsLoading(false);
}
}, [direction, initialLimit, isLoading, orderBy]);

const refresh = useCallback(async () => {
setIsRefreshing(true);
setNextCursor(null);
setHasMore(true);
setItems([]);

try {
await fetchPage();
} finally {
setIsRefreshing(false);
}
}, [fetchPage]);

const loadNextPage = useCallback(async () => {
if (!hasMore || isLoading) {
return;
}

await fetchPage(nextCursor ?? undefined);
}, [fetchPage, hasMore, isLoading, nextCursor]);

useEffect(() => {
void refresh();
}, [refresh]);

return {
items,
isLoading,
isRefreshing,
hasMore,
nextCursor,
loadNextPage,
refresh,
};
}
21 changes: 21 additions & 0 deletions src/services/api/courseApi.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { Course } from "../../types/course";
import apiClient from "./axios.config";
import { fetchWithSWR, invalidateCache } from "./cache";
import {
buildCursorCacheKey,
CursorPageRequest,
CursorPageResponse,
} from "./cursorPagination";

const COURSES_KEY = "courses:list";
const courseKey = (id: string) => `courses:${id}`;
Expand All @@ -19,6 +24,22 @@ export const courseApi = {
);
},

getCoursesPage(request: CursorPageRequest = {}): Promise<CursorPageResponse<Course>> {
const { limit = 20, cursor, orderBy = 'id', direction = 'asc' } = request;
const cacheKey = buildCursorCacheKey({ limit, cursor, orderBy, direction });

return fetchWithSWR(
cacheKey,
() => apiClient
.get<CursorPageResponse<Course>>("/courses", {
params: { limit, cursor, orderBy, direction },
})
.then((r) => r.data),
TTL,
STALE_TTL,
);
},

getCourse(id: string): Promise<Course> {
return fetchWithSWR(
courseKey(id),
Expand Down
Loading
Loading