2023-03-09 09:23:14 -08:00
|
|
|
import { useEntities, useEntity } from 'soapbox/entity-store/hooks';
|
2023-03-10 11:36:00 -08:00
|
|
|
import { groupSchema, Group } from 'soapbox/schemas/group';
|
|
|
|
import { groupRelationshipSchema, GroupRelationship } from 'soapbox/schemas/group-relationship';
|
2023-03-09 09:21:27 -08:00
|
|
|
|
|
|
|
function useGroups() {
|
2023-03-13 14:23:11 -07:00
|
|
|
const { entities, ...result } = useEntities<Group>(['Group', ''], '/api/v1/groups', { schema: groupSchema });
|
2023-03-09 13:05:54 -08:00
|
|
|
const { relationships } = useGroupRelationships(entities.map(entity => entity.id));
|
2023-03-09 09:21:27 -08:00
|
|
|
|
2023-03-10 11:36:00 -08:00
|
|
|
const groups = entities.map((group) => ({ ...group, relationship: relationships[group.id] || null }));
|
2023-03-09 09:47:24 -08:00
|
|
|
|
2023-03-09 09:21:27 -08:00
|
|
|
return {
|
|
|
|
...result,
|
2023-03-09 09:47:24 -08:00
|
|
|
groups,
|
2023-03-09 09:21:27 -08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2023-03-09 13:05:54 -08:00
|
|
|
function useGroup(groupId: string, refetch = true) {
|
2023-03-13 14:23:11 -07:00
|
|
|
const { entity: group, ...result } = useEntity<Group>(['Group', groupId], `/api/v1/groups/${groupId}`, { schema: groupSchema, refetch });
|
2023-03-09 13:05:54 -08:00
|
|
|
const { entity: relationship } = useGroupRelationship(groupId);
|
2023-03-09 09:23:14 -08:00
|
|
|
|
|
|
|
return {
|
|
|
|
...result,
|
2023-03-10 11:36:00 -08:00
|
|
|
group: group ? { ...group, relationship: relationship || null } : undefined,
|
2023-03-09 10:36:20 -08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
function useGroupRelationship(groupId: string) {
|
2023-03-13 14:23:11 -07:00
|
|
|
return useEntity<GroupRelationship>(['GroupRelationship', groupId], `/api/v1/groups/relationships?id[]=${groupId}`, { schema: groupRelationshipSchema });
|
2023-03-09 09:23:14 -08:00
|
|
|
}
|
|
|
|
|
2023-03-09 09:47:24 -08:00
|
|
|
function useGroupRelationships(groupIds: string[]) {
|
|
|
|
const q = groupIds.map(id => `id[]=${id}`).join('&');
|
2023-03-09 13:05:54 -08:00
|
|
|
const endpoint = groupIds.length ? `/api/v1/groups/relationships?${q}` : undefined;
|
2023-03-13 14:23:11 -07:00
|
|
|
const { entities, ...result } = useEntities<GroupRelationship>(['GroupRelationship', q], endpoint, { schema: groupRelationshipSchema });
|
2023-03-09 09:47:24 -08:00
|
|
|
|
2023-03-09 13:05:54 -08:00
|
|
|
const relationships = entities.reduce<Record<string, GroupRelationship>>((map, relationship) => {
|
|
|
|
map[relationship.id] = relationship;
|
|
|
|
return map;
|
|
|
|
}, {});
|
2023-03-09 09:47:24 -08:00
|
|
|
|
|
|
|
return {
|
|
|
|
...result,
|
2023-03-09 13:05:54 -08:00
|
|
|
relationships,
|
2023-03-09 09:47:24 -08:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2023-03-13 13:08:42 -07:00
|
|
|
export { useGroup, useGroups, useGroupRelationships };
|