shoc-frontend-new/src/api/handle-api-response.ts
Arthur Bassi 6e99dc0af2 refactor(work-orders): pass board-api governance maintainability gate
Split oversized API/mapper/UI modules and extract focused helpers so the
exact head satisfies godfile and complexity ratchets without relaxing thresholds.
2026-07-28 09:56:27 -03:00

62 lines
1.3 KiB
TypeScript

import { readItems, readPage, readPageSize, readTotalCount } from "@/api/paginated-response-fields";
export interface PaginatedResult<T> {
items: T[];
totalCount: number;
page: number;
pageSize: number;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function handleApiResponse<T>(data: unknown): T {
if (Array.isArray(data)) {
return data as T;
}
if (isRecord(data)) {
const nested = data.data ?? data.Data ?? data.value;
if (nested !== undefined) {
return nested as T;
}
}
return data as T;
}
export function handlePaginatedResponse<T>(
data: unknown,
params?: { page?: number; pageSize?: number },
): PaginatedResult<T> {
const page = params?.page ?? 1;
const pageSize = params?.pageSize ?? 12;
if (Array.isArray(data)) {
return {
items: data as T[],
totalCount: data.length,
page,
pageSize,
};
}
if (isRecord(data)) {
const items = readItems<T>(data);
return {
items,
totalCount: readTotalCount(data, items.length),
page: readPage(data, page),
pageSize: readPageSize(data, pageSize),
};
}
return {
items: [],
totalCount: 0,
page,
pageSize,
};
}