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

feat: create useUpdateOptionListIdMutation hook #14181

Merged
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
2 changes: 2 additions & 0 deletions frontend/packages/shared/src/api/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
addImagePath,
optionListUploadPath,
optionListUpdatePath,
optionListIdUpdatePath,
} from 'app-shared/api/paths';
import type { AddLanguagePayload } from 'app-shared/types/api/AddLanguagePayload';
import type { AddRepoParams } from 'app-shared/types/api';
Expand Down Expand Up @@ -118,6 +119,7 @@ export const updateAppConfig = (org: string, app: string, payload: AppConfig) =>
export const uploadDataModel = (org: string, app: string, form: FormData) => post<void, FormData>(dataModelsUploadPath(org, app), form, { headers: { 'Content-Type': 'multipart/form-data' } });
export const uploadOptionList = (org: string, app: string, payload: FormData) => post<void, FormData>(optionListUploadPath(org, app), payload, { headers: { 'Content-Type': 'multipart/form-data' } });
export const updateOptionList = (org: string, app: string, optionsListId: string, payload: Option[]) => put<Option[]>(optionListUpdatePath(org, app, optionsListId), payload);
export const updateOptionListId = (org: string, app: string, optionsListId: string, newOptionsListId: string) => put<void, string>(optionListIdUpdatePath(org, app, optionsListId), JSON.stringify(newOptionsListId), { headers: { 'Content-Type': 'application/json' } });
export const upsertTextResources = (org: string, app: string, language: string, payload: ITextResourcesObjectFormat) => put<ITextResourcesObjectFormat>(textResourcesPath(org, app, language), payload);

// Resourceadm
Expand Down
1 change: 1 addition & 0 deletions frontend/packages/shared/src/api/paths.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export const widgetSettingsPath = (org, app) => `${basePath}/${org}/${app}/app-d
export const optionListsPath = (org, app) => `${basePath}/${org}/${app}/options/option-lists`; // Get
export const optionListIdsPath = (org, app) => `${basePath}/${org}/${app}/app-development/option-list-ids`; // Get
export const optionListUpdatePath = (org, app, optionsListId) => `${basePath}/${org}/${app}/options/${optionsListId}`; // Put
export const optionListIdUpdatePath = (org, app, optionsListId) => `${basePath}/${org}/${app}/options/change-name/${optionsListId}`; // Put
export const optionListUploadPath = (org, app) => `${basePath}/${org}/${app}/options/upload`; // Post
export const ruleConfigPath = (org, app, layoutSetName) => `${basePath}/${org}/${app}/app-development/rule-config?${s({ layoutSetName })}`; // Get, Post
export const appMetadataModelIdsPath = (org, app, onlyUnReferenced) => `${basePath}/${org}/${app}/app-development/model-ids?${s({ onlyUnReferenced })}`; // Get
Expand Down
1 change: 1 addition & 0 deletions frontend/packages/shared/src/hooks/mutations/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { useAddOptionListMutation } from './useAddOptionListMutation';
export { useUpdateOptionListMutation } from './useUpdateOptionListMutation';
export { useUpdateOptionListIdMutation } from './useUpdateOptionListIdMutation';
export { useUpsertTextResourcesMutation } from './useUpsertTextResourcesMutation';
export { useUpsertTextResourceMutation } from './useUpsertTextResourceMutation';
export { useRepoCommitAndPushMutation } from './useRepoCommitAndPushMutation';
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { app, org } from '@studio/testing/testids';
import { queriesMock } from 'app-shared/mocks/queriesMock';
import { renderHookWithProviders } from 'app-shared/mocks/renderHookWithProviders';
import type { UpdateOptionListIdMutationArgs } from './useUpdateOptionListIdMutation';
import { useUpdateOptionListIdMutation } from './useUpdateOptionListIdMutation';
import { createQueryClientMock } from 'app-shared/mocks/queryClientMock';
import { QueryKey } from 'app-shared/types/QueryKey';
import type { Option } from 'app-shared/types/Option';
import type { OptionsLists } from 'app-shared/types/api/OptionsLists';

// Test data:
const optionListId: string = 'optionListId';
const newOptionListId: string = 'newOptionListId';
const optionListMock: Option[] = [{ value: 'value', label: 'label' }];
const args: UpdateOptionListIdMutationArgs = { optionListId, newOptionListId };

describe('useUpdateOptionListIdMutation', () => {
test('Calls useUpdateOptionIdList with correct parameters', async () => {
const queryClient = createQueryClientMock();
queryClient.setQueryData([QueryKey.OptionLists, org, app], [{ optionListId: optionListMock }]);
const renderUpdateOptionListMutationResult = renderHookWithProviders(
() => useUpdateOptionListIdMutation(org, app),
{ queryClient },
).result;
await renderUpdateOptionListMutationResult.current.mutateAsync(args);
expect(queriesMock.updateOptionListId).toHaveBeenCalledTimes(1);
expect(queriesMock.updateOptionListId).toHaveBeenCalledWith(
org,
app,
optionListId,
newOptionListId,
);
});

test('Sets the option lists cache with new id in correct alphabetical order', async () => {
const queryClient = createQueryClientMock();
const oldData: OptionsLists = {
optionListA: optionListMock,
optionListB: optionListMock,
optionListZ: optionListMock,
};
queryClient.setQueryData([QueryKey.OptionLists, org, app], oldData);
const renderUpdateOptionListMutationResult = renderHookWithProviders(
() => useUpdateOptionListIdMutation(org, app),
{ queryClient },
).result;
await renderUpdateOptionListMutationResult.current.mutateAsync({
optionListId: 'optionListA',
newOptionListId: 'optionListC',
});
const cacheData = queryClient.getQueryData([QueryKey.OptionLists, org, app]);
expect(cacheData).toEqual({
optionListB: optionListMock,
optionListC: optionListMock,
optionListZ: optionListMock,
});
TomasEng marked this conversation as resolved.
Show resolved Hide resolved
});

test('Invalidates the optionListIds query cache', async () => {
const queryClient = createQueryClientMock();
const invalidateQueriesSpy = jest.spyOn(queryClient, 'invalidateQueries');
const oldData: OptionsLists = {
firstOptionList: optionListMock,
optionListId: optionListMock,
lastOptionList: optionListMock,
};
queryClient.setQueryData([QueryKey.OptionLists, org, app], oldData);
const renderUpdateOptionListMutationResult = renderHookWithProviders(
() => useUpdateOptionListIdMutation(org, app),
{ queryClient },
).result;
await renderUpdateOptionListMutationResult.current.mutateAsync(args);
expect(invalidateQueriesSpy).toHaveBeenCalledTimes(1);
expect(invalidateQueriesSpy).toHaveBeenCalledWith({
queryKey: [QueryKey.OptionListIds, org, app],
});
TomasEng marked this conversation as resolved.
Show resolved Hide resolved
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { QueryKey } from 'app-shared/types/QueryKey';
import type { OptionsLists } from 'app-shared/types/api/OptionsLists';
import { useQueryClient, useMutation } from '@tanstack/react-query';
import { useServicesContext } from 'app-shared/contexts/ServicesContext';

export interface UpdateOptionListIdMutationArgs {
optionListId: string;
newOptionListId: string;
}

export const useUpdateOptionListIdMutation = (org: string, app: string) => {
const queryClient = useQueryClient();
const { updateOptionListId } = useServicesContext();

return useMutation({
mutationFn: async ({ optionListId, newOptionListId }: UpdateOptionListIdMutationArgs) => {
return updateOptionListId(org, app, optionListId, newOptionListId).then(() => ({
optionListId,
newOptionListId,
}));
},
onSuccess: ({ optionListId, newOptionListId }) => {
const oldData: OptionsLists = queryClient.getQueryData([QueryKey.OptionLists, org, app]);
const ascSortedData = ChangeIdAndSortCacheData(optionListId, newOptionListId, oldData);
queryClient.setQueryData([QueryKey.OptionLists, org, app], ascSortedData);
queryClient.invalidateQueries({ queryKey: [QueryKey.OptionListIds, org, app] });
},
});
};

const ChangeIdAndSortCacheData = (
TomasEng marked this conversation as resolved.
Show resolved Hide resolved
oldId: string,
newId: string,
oldData: OptionsLists,
): OptionsLists => {
const newData = { ...oldData };
delete newData[oldId];
newData[newId] = oldData[oldId];
return Object.fromEntries(
Object.entries(newData).sort(([keyA], [keyB]) => keyA.localeCompare(keyB)),
);
TomasEng marked this conversation as resolved.
Show resolved Hide resolved
};
1 change: 1 addition & 0 deletions frontend/packages/shared/src/mocks/queriesMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ export const queriesMock: ServicesContextProps = {
updateAppMetadata: jest.fn().mockImplementation(() => Promise.resolve()),
updateAppConfig: jest.fn().mockImplementation(() => Promise.resolve()),
updateOptionList: jest.fn().mockImplementation(() => Promise.resolve()),
updateOptionListId: jest.fn().mockImplementation(() => Promise.resolve()),
uploadDataModel: jest.fn().mockImplementation(() => Promise.resolve<JsonSchema>({})),
uploadOptionList: jest.fn().mockImplementation(() => Promise.resolve()),
upsertTextResources: jest
Expand Down