import { FractalPaginatedResponse, FractalResponseData, FractalResponseList, getPaginationSet, PaginatedResult, } from '@/api/http'; import { Model } from '@definitions/index'; type TransformerFunc = (callback: FractalResponseData) => T; const isList = (data: FractalResponseList | FractalResponseData): data is FractalResponseList => data.object === 'list'; function transform(data: null | undefined, transformer: TransformerFunc, missing?: M): M; function transform( data: FractalResponseData | null | undefined, transformer: TransformerFunc, missing?: M ): T | M; function transform( data: FractalResponseList | FractalPaginatedResponse | null | undefined, transformer: TransformerFunc, missing?: M ): T[] | M; function transform( data: FractalResponseData | FractalResponseList | FractalPaginatedResponse | null | undefined, transformer: TransformerFunc, missing = undefined ) { if (data === undefined || data === null) { return missing; } if (isList(data)) { return data.data.map(transformer); } if (!data || !data.attributes || data.object === 'null_resource') { return missing; } return transformer(data); } function toPaginatedSet>( response: FractalPaginatedResponse, transformer: T ): PaginatedResult> { return { items: transform(response, transformer) as ReturnType[], pagination: getPaginationSet(response.meta.pagination), }; } export { transform, toPaginatedSet };