2022-06-05 22:35:53 +00:00
|
|
|
import {
|
|
|
|
FractalPaginatedResponse,
|
|
|
|
FractalResponseData,
|
|
|
|
FractalResponseList,
|
|
|
|
getPaginationSet,
|
|
|
|
PaginatedResult,
|
|
|
|
} from '@/api/http';
|
|
|
|
import { Model } from '@definitions/index';
|
2022-05-30 00:34:48 +00:00
|
|
|
|
2022-06-05 22:35:53 +00:00
|
|
|
type TransformerFunc<T> = (callback: FractalResponseData) => T;
|
2022-05-30 00:34:48 +00:00
|
|
|
|
|
|
|
const isList = (data: FractalResponseList | FractalResponseData): data is FractalResponseList => data.object === 'list';
|
|
|
|
|
2022-06-05 22:35:53 +00:00
|
|
|
function transform<T, M>(data: null | undefined, transformer: TransformerFunc<T>, missing?: M): M;
|
2022-06-26 19:13:52 +00:00
|
|
|
function transform<T, M>(
|
|
|
|
data: FractalResponseData | null | undefined,
|
|
|
|
transformer: TransformerFunc<T>,
|
2022-11-25 20:25:03 +00:00
|
|
|
missing?: M,
|
2022-06-26 19:13:52 +00:00
|
|
|
): T | M;
|
|
|
|
function transform<T, M>(
|
|
|
|
data: FractalResponseList | FractalPaginatedResponse | null | undefined,
|
|
|
|
transformer: TransformerFunc<T>,
|
2022-11-25 20:25:03 +00:00
|
|
|
missing?: M,
|
2022-06-26 19:13:52 +00:00
|
|
|
): T[] | M;
|
|
|
|
function transform<T>(
|
|
|
|
data: FractalResponseData | FractalResponseList | FractalPaginatedResponse | null | undefined,
|
|
|
|
transformer: TransformerFunc<T>,
|
2022-11-25 20:25:03 +00:00
|
|
|
missing = undefined,
|
2022-06-26 19:13:52 +00:00
|
|
|
) {
|
2022-05-30 00:34:48 +00:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2022-06-26 19:13:52 +00:00
|
|
|
function toPaginatedSet<T extends TransformerFunc<Model>>(
|
2022-06-05 22:35:53 +00:00
|
|
|
response: FractalPaginatedResponse,
|
2022-11-25 20:25:03 +00:00
|
|
|
transformer: T,
|
2022-06-05 22:35:53 +00:00
|
|
|
): PaginatedResult<ReturnType<T>> {
|
|
|
|
return {
|
|
|
|
items: transform(response, transformer) as ReturnType<T>[],
|
|
|
|
pagination: getPaginationSet(response.meta.pagination),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export { transform, toPaginatedSet };
|