Skip to content

Commit

Permalink
More fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
denniskigen committed Sep 19, 2024
1 parent 7575569 commit 4336050
Show file tree
Hide file tree
Showing 8 changed files with 23 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import uniq from 'lodash-es/uniq';
import useSWR from 'swr';
import { fetchPatientData, getFullSynchronizationItems, type SyncItem } from '@openmrs/esm-framework/src/internal';
import { fetchCurrentPatient, getFullSynchronizationItems, type SyncItem } from '@openmrs/esm-framework/src/internal';

export function usePendingSyncItems() {
return useSWR('offlineActions/pending', () => getFullSynchronizationItems());
Expand All @@ -11,6 +11,6 @@ export function useSyncItemPatients(syncItems?: Array<SyncItem>) {

return useSWR(
() => ['patients', ...patientUuids],
() => Promise.all(patientUuids.map((id) => fetchPatientData(id, true))),
() => Promise.all(patientUuids.map((id) => fetchCurrentPatient(id))),
);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import useSWR, { type SWRResponse } from 'swr';
import { fetchPatientData, getSynchronizationItems, getDynamicOfflineDataEntries } from '@openmrs/esm-framework';
import { fetchCurrentPatient, getSynchronizationItems, getDynamicOfflineDataEntries } from '@openmrs/esm-framework';
import merge from 'lodash-es/merge';

function useDynamicOfflineDataEntries(type: string) {
Expand All @@ -14,7 +14,7 @@ function useSynchronizationItems<T>(type: string) {
function useFhirPatients(ids: Array<string>) {
const stableIds = useMemo(() => [...ids].sort(), [ids]);
return useSWR(['fhirPatients', stableIds], () =>
Promise.all(stableIds.map((patientId) => fetchPatientData(patientId, false, undefined))),
Promise.all(stableIds.map((patientId) => fetchCurrentPatient(patientId, undefined, false))),
);
}

Expand Down
16 changes: 2 additions & 14 deletions packages/apps/esm-offline-tools-app/src/offline.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import {
type FetchConfig,
fhirBaseUrl,
fetchCurrentPatient,
makeUrl,
messageOmrsServiceWorker,
openmrsFetch,
setupDynamicOfflineDataHandler,
} from '@openmrs/esm-framework';
import { cacheForOfflineHeaders } from './constants';
Expand All @@ -26,19 +24,9 @@ export function setupOffline() {
pattern: `/ws/fhir2/R4/Patient/${identifier}`,
});

await fetchPatientData(identifier, {
await fetchCurrentPatient(identifier, {
headers: cacheForOfflineHeaders,
});
},
});
}

export async function fetchPatientData(patientUuid: string, fetchInit?: FetchConfig): Promise<fhir.Patient | null> {
try {
const onlinePatient = await openmrsFetch<fhir.Patient>(`${fhirBaseUrl}/Patient/${patientUuid}`, fetchInit);
return onlinePatient.data;
} catch (err) {
console.error('Failed to fetch patient online:', err);
return null;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getSynchronizationItems } from '@openmrs/esm-offline';
import { type FetchResponse } from '../types';
import { fetchPatientData } from './current-patient';
import { fetchCurrentPatient } from './current-patient';
import { openmrsFetch } from '../openmrs-fetch';

const mockOpenmrsFetch = jest.mocked(openmrsFetch);
Expand All @@ -22,15 +22,15 @@ describe('fetchPatientData', () => {
});

it('should return null when patientUuid is falsy', async () => {
const result = await fetchPatientData('', true);
const result = await fetchCurrentPatient('');
expect(result).toBeNull();
});

it('should return online patient data when available', async () => {
const mockPatient = { id: '123', name: [{ given: ['John'], family: 'Doe' }] };
mockOpenmrsFetch.mockResolvedValue({ data: mockPatient, ok: true } as Partial<FetchResponse> as FetchResponse);

const result = await fetchPatientData('123', true);
const result = await fetchCurrentPatient('123');
expect(result).toEqual(mockPatient);
});

Expand All @@ -39,14 +39,14 @@ describe('fetchPatientData', () => {
mockOpenmrsFetch.mockRejectedValue(new Error('Network error'));
mockGetSynchronizationItems.mockResolvedValue([{ fhirPatient: mockOfflinePatient }]);

const result = await fetchPatientData('123', true);
const result = await fetchCurrentPatient('123');
expect(result).toEqual(mockOfflinePatient);
});

it('should throw an error when both online and offline fetches fail', async () => {
mockOpenmrsFetch.mockRejectedValue(new Error('Network error'));
mockGetSynchronizationItems.mockResolvedValue([]);

await expect(fetchPatientData('123', true)).rejects.toThrow('Network error');
await expect(fetchCurrentPatient('123')).rejects.toThrow('Network error');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ export interface OnlyThePatient extends CurrentPatientOptions {

export type PatientUuid = string | null;

export async function fetchPatientData(
patientUuid: string,
includeOfflinePatients: boolean = true,
export async function fetchCurrentPatient(
patientUuid: PatientUuid,
fetchInit?: FetchConfig,
includeOfflinePatients: boolean = true,
): Promise<fhir.Patient | null> {
if (patientUuid) {
let err: Error | null = null;
Expand Down
10 changes: 5 additions & 5 deletions packages/framework/esm-framework/docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
- [clearCurrentUser](API.md#clearcurrentuser)
- [createAttachment](API.md#createattachment)
- [deleteAttachmentPermanently](API.md#deleteattachmentpermanently)
- [fetchPatientData](API.md#fetchpatientdata)
- [fetchCurrentPatient](API.md#fetchcurrentpatient)
- [getAttachmentByUuid](API.md#getattachmentbyuuid)
- [getAttachments](API.md#getattachments)
- [getCurrentUser](API.md#getcurrentuser)
Expand Down Expand Up @@ -2200,17 +2200,17 @@ ___

___

### fetchPatientData
### fetchCurrentPatient

**fetchPatientData**(`patientUuid`, `includeOfflinePatients?`, `fetchInit?`): `Promise`<`fhir.Patient` \| ``null``\>
**fetchCurrentPatient**(`patientUuid`, `fetchInit?`, `includeOfflinePatients?`): `Promise`<`fhir.Patient` \| ``null``\>

#### Parameters

| Name | Type | Default value |
| :------ | :------ | :------ |
| `patientUuid` | `string` | `undefined` |
| `includeOfflinePatients` | `boolean` | `true` |
| `patientUuid` | [`PatientUuid`](API.md#patientuuid) | `undefined` |
| `fetchInit?` | [`FetchConfig`](interfaces/FetchConfig.md) | `undefined` |
| `includeOfflinePatients` | `boolean` | `true` |

#### Returns

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,8 @@ const defaultSwrConfig = {
errorRetryCount: 3,
// default fetcher function
fetcher: openmrsFetch,
// only revalidate once every 10 minutes
focusThrottleInterval: 600000,
// disable automatic revalidations by default
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
// only revalidate once every 30 seconds
focusThrottleInterval: 30000,
};

export interface ComponentDecoratorOptions {
Expand Down
4 changes: 2 additions & 2 deletions packages/framework/esm-react-utils/src/usePatient.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** @module @category API */
import { useEffect, useMemo, useState } from 'react';
import useSWR from 'swr';
import { fetchPatientData } from '@openmrs/esm-api';
import { fetchCurrentPatient } from '@openmrs/esm-api';

export type NullablePatient = fhir.Patient | null;

Expand All @@ -24,7 +24,7 @@ export function usePatient(patientUuid?: string) {
error,
isValidating,
} = useSWR<NullablePatient>(currentPatientUuid ? ['patient', currentPatientUuid] : null, () =>
fetchPatientData(currentPatientUuid!, true, {}),
fetchCurrentPatient(currentPatientUuid!, {}),
);

useEffect(() => {
Expand Down

0 comments on commit 4336050

Please sign in to comment.