import { useEffect } from 'react'; import { PractitionerRole } from 'fhir/r4'; import { usePractitionerServiceContext, useFhirServiceContext, useWebSocketServiceContext } from '../services'; export const useFhirPractitionerRoleBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { setPractitionersList } = usePractitionerServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { const handlePractitionerRoleEvent = (cloudEvent: any) => { const practitionerRole: PractitionerRole = cloudEvent.data; const eventType = cloudEvent.type; const practitionerId = extractReferenceId(practitionerRole.practitioner); if (practitionerId) { setPractitionersList(prev => { return prev.map(practitionerWithRoles => { if (practitionerWithRoles.practitioner.id === practitionerId) { switch (eventType) { case 'com.akashichealthrecords.fhir.practitionerrole.created': // Same race as every other created append: the staff list // also refetches after a write, so a role the refetch already brought // in was being added a second time - the same person listed twice // under one practitioner. The `updated` arm below already keys on id. return { ...practitionerWithRoles, roles: practitionerWithRoles.roles.some(role => role.id === practitionerRole.id) ? practitionerWithRoles.roles.map(role => role.id === practitionerRole.id ? practitionerRole : role) : [...practitionerWithRoles.roles, practitionerRole] }; case 'com.akashichealthrecords.fhir.practitionerrole.updated': return { ...practitionerWithRoles, roles: practitionerWithRoles.roles.map(role => role.id === practitionerRole.id ? practitionerRole : role) }; case 'com.akashichealthrecords.fhir.practitionerrole.deleted': return { ...practitionerWithRoles, roles: practitionerWithRoles.roles.filter(role => role.id !== practitionerRole.id) }; return practitionerWithRoles; } } return practitionerWithRoles; }); }); } }; subscribe('com.akashichealthrecords.fhir.practitionerrole.created', handlePractitionerRoleEvent); subscribe('com.akashichealthrecords.fhir.practitionerrole.updated', handlePractitionerRoleEvent); subscribe('com.akashichealthrecords.fhir.practitionerrole.deleted', handlePractitionerRoleEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.practitionerrole.created', handlePractitionerRoleEvent); unsubscribe('com.akashichealthrecords.fhir.practitionerrole.updated', handlePractitionerRoleEvent); unsubscribe('com.akashichealthrecords.fhir.practitionerrole.deleted', handlePractitionerRoleEvent); }; }, [subscribe, unsubscribe, extractReferenceId, setPractitionersList]); };