import { useEffect } from 'react'; import { Goal } from 'fhir/r4'; import { useGoalServiceContext, useFhirServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; export const useFhirGoalBroadcast = () => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { goalsList, publishGoal, readGoalForEvent } = useGoalServiceContext(); const { patientState } = usePatientServiceContext(); const { extractReferenceId } = useFhirServiceContext(); useEffect(() => { if (!patientState) { return; } const handleGoalEvent = (cloudEvent: any) => { const goal: Goal = cloudEvent.data; const eventType = cloudEvent.type; const patientId = extractReferenceId(goal.subject); if (patientState.id !== patientId || !goal.id) return; // A deletion clears it at once; any other change is read again, since what an event carries is not shown. if (eventType === 'com.akashichealthrecords.fhir.goal.deleted') publishGoal(goal, 'deleted'); else void readGoalForEvent(goal.id, cloudEvent); }; subscribe('com.akashichealthrecords.fhir.goal.created', handleGoalEvent); subscribe('com.akashichealthrecords.fhir.goal.updated', handleGoalEvent); subscribe('com.akashichealthrecords.fhir.goal.deleted', handleGoalEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.goal.created', handleGoalEvent); unsubscribe('com.akashichealthrecords.fhir.goal.updated', handleGoalEvent); unsubscribe('com.akashichealthrecords.fhir.goal.deleted', handleGoalEvent); }; }, [patientState, subscribe, unsubscribe, extractReferenceId, goalsList, publishGoal, readGoalForEvent]); };