deduplicateById: fix Entity types

This commit is contained in:
Alex Gleason 2022-12-06 14:48:41 -06:00
parent 569296af36
commit f7bd5c5951
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
1 changed files with 13 additions and 4 deletions

View File

@ -8,10 +8,17 @@ export interface PaginatedResult<T> {
link?: string,
}
interface Entity {
id: string,
}
const isEntity = <T = unknown>(object: T): object is T & Entity => {
return object && typeof object === 'object' && 'id' in object;
};
/** Deduplicate an array of entities by their ID. */
const deduplicate = <T>(entities: T[]): T[] => {
const deduplicateById = <T extends Entity>(entities: T[]): T[] => {
const map = entities.reduce<Map<string, T>>((result, entity) => {
// @ts-expect-error Entity might not have an ID... but it probably does.
return result.set(entity.id, entity);
}, new Map());
@ -26,8 +33,10 @@ const flattenPages = <T>(queryData: InfiniteData<PaginatedResult<T>> | undefined
[],
);
if (data) {
return deduplicate<T>(data);
if (data && data.every(isEntity)) {
return deduplicateById(data);
} else if (data) {
return data;
}
};