pleroma/app/soapbox/hooks/useGroups.ts

48 lines
1.8 KiB
TypeScript
Raw Normal View History

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