misc_pterodactyl-panel/resources/scripts/api/definitions/helpers.ts

56 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2022-06-05 22:35:53 +00:00
import {
FractalPaginatedResponse,
FractalResponseData,
FractalResponseList,
getPaginationSet,
PaginatedResult,
} from '@/api/http';
import { Model } from '@definitions/index';
2022-06-05 22:35:53 +00:00
type TransformerFunc<T> = (callback: FractalResponseData) => T;
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;
function transform<T, M>(
data: FractalResponseData | null | undefined,
transformer: TransformerFunc<T>,
missing?: M
): T | M;
function transform<T, M>(
data: FractalResponseList | FractalPaginatedResponse | null | undefined,
transformer: TransformerFunc<T>,
missing?: M
): T[] | M;
function transform<T>(
data: FractalResponseData | FractalResponseList | FractalPaginatedResponse | null | undefined,
transformer: TransformerFunc<T>,
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<T extends TransformerFunc<Model>>(
2022-06-05 22:35:53 +00:00
response: FractalPaginatedResponse,
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 };