Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(client): correct loading behavior, add MedplumClient lifecycle events #4701

Merged
merged 4 commits into from
Jun 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
test(client): refreshProfile() sets isLoading() === true again
  • Loading branch information
ThatOneBro committed Jun 20, 2024
commit daf66c9b524a4dd47ab16089f4e25e63cd3fe416
5 changes: 5 additions & 0 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -682,9 +682,13 @@ export interface RequestProfileSchemaOptions {
expandProfile?: boolean;
}

/**
* This map enumerates all the lifecycle events that `MedplumClient` emits and what the shape of the `Event` is.
*/
export type MedplumClientEventMap = {
change: { type: 'change' };
offline: { type: 'offline' };
profileRefreshing: { type: 'profileRefreshing' };
profileRefreshed: { type: 'profileRefreshed' };
storageInitialized: { type: 'storageInitialized' };
};
Expand Down Expand Up @@ -2722,6 +2726,7 @@ export class MedplumClient extends TypedEventTarget<MedplumClientEventMap> {
return Promise.resolve(undefined);
}
this.profilePromise = new Promise((resolve, reject) => {
this.dispatchEvent({ type: 'profileRefreshing' });
this.get('auth/me')
.then((result: SessionDetails) => {
this.profilePromise = undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ describe('MedplumProvider', () => {
act(() => {
storage = new MockAsyncClientStorage();
storage.setObject('activeLogin', {
// This access token contains a field `login_id` which is necessary to pass the validation required in `isMedplumAccessToken`
// to get into the state of `MedplumClient.medplumServer === true`
accessToken:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyLCJsb2dpbl9pZCI6InRlc3RpbmcxMjMifQ.lJGCbp2taTarRbamxaKFsTR_VRVgzvttKMmI5uFQSM0',
refreshToken: '456',
Expand Down Expand Up @@ -201,6 +203,7 @@ describe('MedplumProvider', () => {
reference: 'Project/123',
},
});

let medplum!: MockClient;
const router = new FhirRouter();
const repo = new MemoryRepository();
Expand Down Expand Up @@ -233,5 +236,93 @@ describe('MedplumProvider', () => {

mockFetchSpy.mockRestore();
});

test('Refreshing profile re-triggers loading', async () => {
const baseUrl = 'https://example.com/';
const storage = new ClientStorage(new MemoryStorage());
storage.setObject('activeLogin', {
accessToken:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyLCJsb2dpbl9pZCI6InRlc3RpbmcxMjMifQ.lJGCbp2taTarRbamxaKFsTR_VRVgzvttKMmI5uFQSM0',
refreshToken: '456',
profile: {
reference: 'Practitioner/123',
},
project: {
reference: 'Project/123',
},
});

let medplum!: MockClient;
const router = new FhirRouter();
const repo = new MemoryRepository();
const client = new MockFetchClient(router, repo, baseUrl);
const mockFetchSpy = jest.spyOn(client, 'mockFetch');
let dispatchEventSpy!: jest.SpyInstance;

act(() => {
medplum = new MockClient({
storage,
mockFetchOverride: { router, repo, client },
});
dispatchEventSpy = jest.spyOn(medplum, 'dispatchEvent');
});

expect(medplum.isLoading()).toEqual(true);

act(() => {
render(
<MedplumProvider medplum={medplum}>
<MyComponent />
</MedplumProvider>
);
});

expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(medplum.isLoading()).toEqual(true);

expect(await screen.findByText('Loaded!')).toBeInTheDocument();
expect(medplum.isLoading()).toEqual(false);
expect(mockFetchSpy).toHaveBeenCalledWith(`${baseUrl}auth/me`, expect.objectContaining({ method: 'GET' }));
expect(dispatchEventSpy).toHaveBeenCalledWith({ type: 'profileRefreshed' });

mockFetchSpy.mockClear();
dispatchEventSpy.mockClear();

let loginPromise!: Promise<void>;

act(() => {
// We clear the active login so that we can test what happens when we call `getProfileAsync()`
// Which we want to call `refreshProfile()`
// Which is only possible if `sessionDetails` is not defined
medplum.clearActiveLogin();
medplum.setAccessToken(
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyLCJsb2dpbl9pZCI6InRlc3RpbmcxMjMifQ.lJGCbp2taTarRbamxaKFsTR_VRVgzvttKMmI5uFQSM0'
);
// This is what is testing that we go back to a loading state when profile is being refreshed
loginPromise = medplum.setActiveLogin({
accessToken:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyLCJsb2dpbl9pZCI6InRlc3RpbmcxMjMifQ.lJGCbp2taTarRbamxaKFsTR_VRVgzvttKMmI5uFQSM0',
refreshToken: '456',
profile: {
reference: 'Practitioner/123',
},
project: {
reference: 'Project/123',
},
});
});

expect(medplum.isLoading()).toEqual(true);
expect(await screen.findByText('Loading...')).toBeInTheDocument();
expect(dispatchEventSpy).toHaveBeenCalledWith({ type: 'profileRefreshing' });

expect(await screen.findByText('Loaded!')).toBeInTheDocument();
expect(medplum.isLoading()).toEqual(false);
expect(dispatchEventSpy).toHaveBeenCalledWith({ type: 'profileRefreshed' });

await loginPromise;

expect(mockFetchSpy).toHaveBeenCalledWith(`${baseUrl}auth/me`, expect.objectContaining({ method: 'GET' }));
});
});
});
10 changes: 6 additions & 4 deletions packages/react-hooks/src/MedplumProvider/MedplumProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,23 +28,25 @@ export function MedplumProvider(props: MedplumProviderProps): JSX.Element {

useEffect(() => {
function eventListener(): void {
setState({
...state,
setState((s) => ({
...s,
profile: medplum.getProfile(),
loading: medplum.isLoading(),
});
}));
}

medplum.addEventListener('change', eventListener);
medplum.addEventListener('storageInitialized', eventListener);
medplum.addEventListener('profileRefreshing', eventListener);
medplum.addEventListener('profileRefreshed', eventListener);

return () => {
medplum.removeEventListener('change', eventListener);
medplum.removeEventListener('storageInitialized', eventListener);
medplum.removeEventListener('profileRefreshing', eventListener);
medplum.removeEventListener('profileRefreshed', eventListener);
};
}, [medplum, state]);
}, [medplum]);

const medplumContext = useMemo(
() => ({
Expand Down
Loading