Skip to content

Commit

Permalink
feat: handle reactquery key and self contain widgets
Browse files Browse the repository at this point in the history
  • Loading branch information
simonadomnisoru committed Jan 29, 2024
1 parent 471ea8e commit e4f3399
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 30 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// @flow
/* eslint-disable no-underscore-dangle */
import log from 'loglevel';
import { handleAPIResponse } from 'capture-core/utils/api';
import i18n from '@dhis2/d2-i18n';
import { pipe, errorCreator } from 'capture-core-utils';

Expand All @@ -20,7 +19,14 @@ import { convertFormToClient, convertClientToServer } from '../../../../converte
import { convertOptionSetValue } from '../../../../converters/serverToClient';
import { buildIcon } from '../../../../metaDataMemoryStoreBuilders/common/helpers';
import { OptionGroup } from '../../../../metaData/OptionSet/OptionGroup';
import { getFeatureType, getDataElement, getLabel, isNotValidOptionSet, escapeString } from '../helpers';
import {
getFeatureType,
getDataElement,
getLabel,
isNotValidOptionSet,
escapeString,
handleAPIResponse,
} from '../helpers';
import type { QuerySingleResource } from '../../../../utils/api/api.types';

const OPTION_SET_NOT_FOUND = 'Optionset not found';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// @flow

export const handleAPIResponse = (resourceName: string, apiResponse: any) => {
if (!apiResponse) {
return [];
}
return apiResponse[resourceName] || apiResponse.instances || [];
};
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export { GEOMETRY, getFeatureType, getDataElement, getLabel } from './geometry';
export { convertClientToView } from './convertClientToView';
export { isNotValidOptionSet } from './isNotValidOptionSet';
export { escapeString } from './escapeString';
export { handleAPIResponse } from './handleAPIResponse';
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// @flow
import i18n from '@dhis2/d2-i18n';
import { FEATURES, useFeature } from 'capture-core-utils';
import { useDataEngine, useAlert } from '@dhis2/app-runtime';
import { useMutation, useQueryClient } from 'react-query';
import { handleAPIResponse } from 'capture-core/utils/api';

type Props = {
teiId: string;
Expand All @@ -19,6 +21,7 @@ const addRelationshipMutation = {

export const useAddRelationship = ({ teiId, onMutate, onSuccess }: Props) => {
const queryClient = useQueryClient();
const queryKey: string = useFeature(FEATURES.exportablePayload) ? 'relationships' : 'instances';
const dataEngine = useDataEngine();
const { show: showSnackbar } = useAlert(
i18n.t('An error occurred while adding the relationship'),
Expand All @@ -36,11 +39,12 @@ export const useAddRelationship = ({ teiId, onMutate, onSuccess }: Props) => {
onError: (_, requestData) => {
showSnackbar();
const apiRelationshipId = requestData.clientRelationship.relationship;
const currentRelationships = queryClient.getQueryData([ReactQueryAppNamespace, 'relationships', teiId]);
const apiResponse = queryClient.getQueryData([ReactQueryAppNamespace, 'relationships', teiId]);
const apiRelationships = handleAPIResponse('relationships', apiResponse);

if (!currentRelationships?.instances) return;
if (apiRelationships.length === 0) return;

const newRelationships = currentRelationships.instances.reduce((acc, relationship) => {
const newRelationships = apiRelationships.reduce((acc, relationship) => {
if (relationship.relationship === apiRelationshipId) {
return acc;
}
Expand All @@ -50,26 +54,27 @@ export const useAddRelationship = ({ teiId, onMutate, onSuccess }: Props) => {

queryClient.setQueryData(
[ReactQueryAppNamespace, 'relationships', teiId],
{ instances: newRelationships },
{ [queryKey]: newRelationships },
);
},
onMutate: (...props) => {
onMutate && onMutate(...props);
const { clientRelationship } = props[0];
if (!clientRelationship) return;

queryClient.setQueryData([ReactQueryAppNamespace, 'relationships', teiId], (oldData) => {
const instances = oldData?.instances || [];
const updatedInstances = [clientRelationship, ...instances];
return { instances: updatedInstances };
queryClient.setQueryData([ReactQueryAppNamespace, 'relationships', teiId], (apiResponse) => {
const apiRelationships = handleAPIResponse('relationships', apiResponse);
const updatedInstances = [clientRelationship, ...apiRelationships];
return { [queryKey]: updatedInstances };
});
},
onSuccess: async (apiResponse, requestData) => {
const apiRelationshipId = apiResponse.bundleReport.typeReportMap.RELATIONSHIP.objectReports[0].uid;
const currentRelationships = queryClient.getQueryData([ReactQueryAppNamespace, 'relationships', teiId]);
if (!currentRelationships?.instances) return;
const apiRelationships = handleAPIResponse('relationships', currentRelationships);
if (apiRelationships.length === 0) return;

const newRelationships = currentRelationships.instances.map((relationship) => {
const newRelationships = apiRelationships.map((relationship) => {
if (relationship.relationship === apiRelationshipId) {
return {
...relationship,
Expand All @@ -81,7 +86,7 @@ export const useAddRelationship = ({ teiId, onMutate, onSuccess }: Props) => {

queryClient.setQueryData(
[ReactQueryAppNamespace, 'relationships', teiId],
{ instances: newRelationships },
{ [queryKey]: newRelationships },
);
onSuccess && onSuccess(apiResponse, requestData);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,6 @@ export const getEventListData = async ({
querySingleResource: QuerySingleResource,
}) => {
const mainColumns = getMainColumns(columnsMetaForDataFetching);
// $FlowFixMe
const { eventContainers, pagingData, request } = await getEvents(
createApiQueryArgs(queryArgs, mainColumns, categoryCombinationId),
absoluteApiPath,
Expand Down
2 changes: 1 addition & 1 deletion src/core_modules/capture-core/events/eventRequests.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export async function getEvents(
});

const apiEvents = handleAPIResponse('events', apiResponse);
const eventContainers = await apiEvents.reduce(async (accEventsPromise, apiEvent) => {
const eventContainers: Array<Object> = await apiEvents.reduce(async (accEventsPromise, apiEvent) => {
const accEvents = await accEventsPromise;
const eventContainer = await convertToClientEvent(apiEvent, absoluteApiPath, querySingleResource);
if (eventContainer) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async function getRelationships(
params: queryParams,
});
const apiRelationships = handleAPIResponse('relationships', apiResponse);
// $FlowFixMe
// $FlowFixMe[missing-annot]
return apiRelationships.map(rel => convertServerRelationshipToClient(rel, relationshipTypes));
}

Expand Down
14 changes: 0 additions & 14 deletions src/core_modules/capture-core/utils/api/handleAPIResponse.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,4 @@
// @flow
import { FEATURES, hasAPISupportForFeature } from 'capture-core-utils';

export const handleAPIResponseByMinorVersion = (
resourceName: string,
apiResponse: any,
minorVersion: string | number,
) => {
if (!apiResponse) {
return [];
}
return hasAPISupportForFeature(minorVersion, FEATURES.exportablePayload)
? apiResponse[resourceName] || []
: apiResponse.instances;
};

export const handleAPIResponse = (resourceName: string, apiResponse: any) => {
if (!apiResponse) {
Expand Down

0 comments on commit e4f3399

Please sign in to comment.