73 lines
1.7 KiB
TypeScript
73 lines
1.7 KiB
TypeScript
import { MatchableEntity } from "./types";
|
|
|
|
const DEFAULT_COLLECTION_KEYS = ["data", "items"];
|
|
|
|
export function resolveCollection(
|
|
payload: unknown,
|
|
preferredKeys: string[] = []
|
|
): Record<string, unknown>[] {
|
|
if (typeof payload !== "object" || payload === null) {
|
|
return [];
|
|
}
|
|
|
|
const obj = payload as Record<string, unknown>;
|
|
|
|
for (const key of [...preferredKeys, ...DEFAULT_COLLECTION_KEYS]) {
|
|
const maybeCollection = obj?.[key];
|
|
if (Array.isArray(maybeCollection)) {
|
|
return maybeCollection as Record<string, unknown>[];
|
|
}
|
|
}
|
|
|
|
if (Array.isArray(payload)) {
|
|
return payload as Record<string, unknown>[];
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
export function normalizeEntity(
|
|
item: Record<string, unknown>,
|
|
primaryKey: string = "name",
|
|
fallbackId: number
|
|
): MatchableEntity {
|
|
const id = item.id ?? item._id ?? fallbackId;
|
|
const name =
|
|
(item[primaryKey] as string) ||
|
|
(item.name as string) ||
|
|
(item.title as string) ||
|
|
(item.email as string) ||
|
|
`Item ${id}`;
|
|
|
|
return {
|
|
id: String(id),
|
|
name: String(name),
|
|
...item,
|
|
};
|
|
}
|
|
|
|
export function findActiveItem(
|
|
sourceItems: MatchableEntity[],
|
|
targetItems: MatchableEntity[],
|
|
activeId: string
|
|
): MatchableEntity | undefined {
|
|
return [...sourceItems, ...targetItems].find(item => item.id === activeId);
|
|
}
|
|
|
|
export function isItemInSource(
|
|
sourceItems: MatchableEntity[],
|
|
activeId: string
|
|
): boolean {
|
|
return sourceItems.some(item => item.id === activeId);
|
|
}
|
|
|
|
export function addItemIfNotPresent(
|
|
items: MatchableEntity[],
|
|
item: MatchableEntity
|
|
): MatchableEntity[] {
|
|
if (items.some(existingItem => existingItem.id === item.id)) {
|
|
return items;
|
|
}
|
|
return [...items, item];
|
|
}
|