BREAKING CHANGE(core): major architectural refactoring with fetch-like API
This commit is contained in:
@@ -1,19 +1,22 @@
|
||||
import { type IExtendedIncomingMessage } from '../../legacy/smartrequest.request.js';
|
||||
import { type SmartResponse } from '../../core/index.js';
|
||||
import { type TPaginationConfig, PaginationStrategy, type TPaginatedResponse } from '../types/pagination.js';
|
||||
|
||||
/**
|
||||
* Creates a paginated response from a regular response
|
||||
*/
|
||||
export function createPaginatedResponse<T>(
|
||||
response: IExtendedIncomingMessage<any>,
|
||||
export async function createPaginatedResponse<T>(
|
||||
response: SmartResponse<any>,
|
||||
paginationConfig: TPaginationConfig,
|
||||
queryParams: Record<string, string>,
|
||||
fetchNextPage: (params: Record<string, string>) => Promise<TPaginatedResponse<T>>
|
||||
): TPaginatedResponse<T> {
|
||||
): Promise<TPaginatedResponse<T>> {
|
||||
// Parse response body first
|
||||
const body = await response.json();
|
||||
|
||||
// Default to response.body for items if response is JSON
|
||||
let items: T[] = Array.isArray(response.body)
|
||||
? response.body
|
||||
: (response.body?.items || response.body?.data || response.body?.results || []);
|
||||
let items: T[] = Array.isArray(body)
|
||||
? body
|
||||
: (body?.items || body?.data || body?.results || []);
|
||||
|
||||
let hasNextPage = false;
|
||||
let nextPageParams: Record<string, string> = {};
|
||||
@@ -24,7 +27,7 @@ export function createPaginatedResponse<T>(
|
||||
const config = paginationConfig;
|
||||
const currentPage = parseInt(queryParams[config.pageParam || 'page'] || String(config.startPage || 1));
|
||||
const limit = parseInt(queryParams[config.limitParam || 'limit'] || String(config.pageSize || 20));
|
||||
const total = getValueByPath(response.body, config.totalPath || 'total') || 0;
|
||||
const total = getValueByPath(body, config.totalPath || 'total') || 0;
|
||||
|
||||
hasNextPage = currentPage * limit < total;
|
||||
|
||||
@@ -39,8 +42,8 @@ export function createPaginatedResponse<T>(
|
||||
|
||||
case PaginationStrategy.CURSOR: {
|
||||
const config = paginationConfig;
|
||||
const nextCursor = getValueByPath(response.body, config.cursorPath || 'nextCursor');
|
||||
const hasMore = getValueByPath(response.body, config.hasMorePath || 'hasMore');
|
||||
const nextCursor = getValueByPath(body, config.cursorPath || 'nextCursor');
|
||||
const hasMore = getValueByPath(body, config.hasMorePath || 'hasMore');
|
||||
|
||||
hasNextPage = !!nextCursor || !!hasMore;
|
||||
|
||||
|
Reference in New Issue
Block a user