Migrated tagEdit reducer to RTK

This commit is contained in:
Alejandro Celaya 2022-11-07 22:12:48 +01:00
parent 648744f440
commit 0571a4a88f
5 changed files with 73 additions and 83 deletions

View file

@ -10,7 +10,6 @@ import orphanVisitsReducer from '../visits/reducers/orphanVisits';
import nonOrphanVisitsReducer from '../visits/reducers/nonOrphanVisits'; import nonOrphanVisitsReducer from '../visits/reducers/nonOrphanVisits';
import tagsListReducer from '../tags/reducers/tagsList'; import tagsListReducer from '../tags/reducers/tagsList';
import tagDeleteReducer from '../tags/reducers/tagDelete'; import tagDeleteReducer from '../tags/reducers/tagDelete';
import tagEditReducer from '../tags/reducers/tagEdit';
import { settingsReducer } from '../settings/reducers/settings'; import { settingsReducer } from '../settings/reducers/settings';
import visitsOverviewReducer from '../visits/reducers/visitsOverview'; import visitsOverviewReducer from '../visits/reducers/visitsOverview';
import { appUpdatesReducer } from '../app/reducers/appUpdates'; import { appUpdatesReducer } from '../app/reducers/appUpdates';
@ -32,7 +31,7 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
nonOrphanVisits: nonOrphanVisitsReducer, nonOrphanVisits: nonOrphanVisitsReducer,
tagsList: tagsListReducer, tagsList: tagsListReducer,
tagDelete: tagDeleteReducer, tagDelete: tagDeleteReducer,
tagEdit: tagEditReducer, tagEdit: container.tagEditReducer,
mercureInfo: container.mercureInfoReducer, mercureInfo: container.mercureInfoReducer,
settings: settingsReducer, settings: settingsReducer,
domainsList: container.domainsListReducer, domainsList: container.domainsListReducer,

View file

@ -1,18 +1,13 @@
import { pick } from 'ramda'; import { pick } from 'ramda';
import { createAction, PayloadAction } from '@reduxjs/toolkit'; import { createAction, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Dispatch } from 'redux'; import { createAsyncThunk } from '../../utils/helpers/redux';
import { buildReducer } from '../../utils/helpers/redux';
import { GetState } from '../../container/types';
import { ColorGenerator } from '../../utils/services/ColorGenerator'; import { ColorGenerator } from '../../utils/services/ColorGenerator';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { parseApiError } from '../../api/utils'; import { parseApiError } from '../../api/utils';
import { ApiErrorAction } from '../../api/types/actions';
import { ProblemDetailsError } from '../../api/types/errors'; import { ProblemDetailsError } from '../../api/types/errors';
export const EDIT_TAG_START = 'shlink/editTag/EDIT_TAG_START'; const EDIT_TAG = 'shlink/editTag/EDIT_TAG';
export const EDIT_TAG_ERROR = 'shlink/editTag/EDIT_TAG_ERROR'; const TAG_EDITED = 'shlink/editTag/TAG_EDITED';
export const EDIT_TAG = 'shlink/editTag/EDIT_TAG';
export const TAG_EDITED = 'shlink/editTag/TAG_EDITED';
export interface TagEdition { export interface TagEdition {
oldName?: string; oldName?: string;
@ -37,35 +32,37 @@ const initialState: TagEdition = {
error: false, error: false,
}; };
export default buildReducer<TagEdition, EditTagAction & ApiErrorAction>({
[EDIT_TAG_START]: () => ({ editing: true, edited: false, error: false }),
[EDIT_TAG_ERROR]: (_, { errorData }) => ({ editing: false, edited: false, error: true, errorData }),
[EDIT_TAG]: (_, { payload }) => ({
...pick(['oldName', 'newName'], payload),
editing: false,
edited: true,
error: false,
}),
}, initialState);
export const editTag = (buildShlinkApiClient: ShlinkApiClientBuilder, colorGenerator: ColorGenerator) => (
{ oldName, newName, color }: EditTag,
) => async (dispatch: Dispatch, getState: GetState) => {
dispatch({ type: EDIT_TAG_START });
const { editTag: shlinkEditTag } = buildShlinkApiClient(getState);
try {
await shlinkEditTag(oldName, newName);
colorGenerator.setColorForKey(newName, color);
dispatch<EditTagAction>({
type: EDIT_TAG,
payload: { oldName, newName, color },
});
} catch (e: any) {
dispatch<ApiErrorAction>({ type: EDIT_TAG_ERROR, errorData: parseApiError(e) });
throw e;
}
};
export const tagEdited = createAction<EditTag>(TAG_EDITED); export const tagEdited = createAction<EditTag>(TAG_EDITED);
export const tagEditReducerCreator = (buildShlinkApiClient: ShlinkApiClientBuilder, colorGenerator: ColorGenerator) => {
const editTag = createAsyncThunk(
EDIT_TAG,
async ({ oldName, newName, color }: EditTag, { getState }): Promise<EditTag> => {
await buildShlinkApiClient(getState).editTag(oldName, newName);
colorGenerator.setColorForKey(newName, color);
return { oldName, newName, color };
},
);
const { reducer } = createSlice({
name: 'tagEditReducer',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(editTag.pending, () => ({ editing: true, edited: false, error: false }));
builder.addCase(
editTag.rejected,
(_, { error }) => ({ editing: false, edited: false, error: true, errorData: parseApiError(error) }),
);
builder.addCase(editTag.fulfilled, (_, { payload }) => ({
...pick(['oldName', 'newName'], payload),
editing: false,
edited: true,
error: false,
}));
},
});
return { reducer, editTag };
};

View file

@ -1,3 +1,4 @@
import { prop } from 'ramda';
import Bottle, { IContainer } from 'bottlejs'; import Bottle, { IContainer } from 'bottlejs';
import { TagsSelector } from '../helpers/TagsSelector'; import { TagsSelector } from '../helpers/TagsSelector';
import { TagCard } from '../TagCard'; import { TagCard } from '../TagCard';
@ -6,7 +7,7 @@ import { EditTagModal } from '../helpers/EditTagModal';
import { TagsList } from '../TagsList'; import { TagsList } from '../TagsList';
import { filterTags, listTags } from '../reducers/tagsList'; import { filterTags, listTags } from '../reducers/tagsList';
import { deleteTag, tagDeleted } from '../reducers/tagDelete'; import { deleteTag, tagDeleted } from '../reducers/tagDelete';
import { editTag, tagEdited } from '../reducers/tagEdit'; import { tagEdited, tagEditReducerCreator } from '../reducers/tagEdit';
import { ConnectDecorator } from '../../container/types'; import { ConnectDecorator } from '../../container/types';
import { TagsCards } from '../TagsCards'; import { TagsCards } from '../TagsCards';
import { TagsTable } from '../TagsTable'; import { TagsTable } from '../TagsTable';
@ -36,6 +37,10 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
['forceListTags', 'filterTags', 'createNewVisits', 'loadMercureInfo'], ['forceListTags', 'filterTags', 'createNewVisits', 'loadMercureInfo'],
)); ));
// Reducers
bottle.serviceFactory('tagEditReducerCreator', tagEditReducerCreator, 'buildShlinkApiClient', 'ColorGenerator');
bottle.serviceFactory('tagEditReducer', prop('reducer'), 'tagEditReducerCreator');
// Actions // Actions
const listTagsActionFactory = (force: boolean) => const listTagsActionFactory = (force: boolean) =>
({ buildShlinkApiClient }: IContainer) => listTags(buildShlinkApiClient, force); ({ buildShlinkApiClient }: IContainer) => listTags(buildShlinkApiClient, force);
@ -43,11 +48,12 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.factory('listTags', listTagsActionFactory(false)); bottle.factory('listTags', listTagsActionFactory(false));
bottle.factory('forceListTags', listTagsActionFactory(true)); bottle.factory('forceListTags', listTagsActionFactory(true));
bottle.serviceFactory('filterTags', () => filterTags); bottle.serviceFactory('filterTags', () => filterTags);
bottle.serviceFactory('tagDeleted', () => tagDeleted);
bottle.serviceFactory('tagEdited', () => tagEdited);
bottle.serviceFactory('deleteTag', deleteTag, 'buildShlinkApiClient'); bottle.serviceFactory('deleteTag', deleteTag, 'buildShlinkApiClient');
bottle.serviceFactory('editTag', editTag, 'buildShlinkApiClient', 'ColorGenerator'); bottle.serviceFactory('tagDeleted', () => tagDeleted);
bottle.serviceFactory('editTag', prop('editTag'), 'tagEditReducerCreator');
bottle.serviceFactory('tagEdited', () => tagEdited);
}; };
export default provideServices; export default provideServices;

View file

@ -1,13 +1,5 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import reducer, { import { tagEdited, EditTagAction, tagEditReducerCreator } from '../../../src/tags/reducers/tagEdit';
EDIT_TAG_START,
EDIT_TAG_ERROR,
EDIT_TAG,
TAG_EDITED,
tagEdited,
editTag,
EditTagAction,
} from '../../../src/tags/reducers/tagEdit';
import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient'; import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ColorGenerator } from '../../../src/utils/services/ColorGenerator'; import { ColorGenerator } from '../../../src/utils/services/ColorGenerator';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
@ -16,10 +8,14 @@ describe('tagEditReducer', () => {
const oldName = 'foo'; const oldName = 'foo';
const newName = 'bar'; const newName = 'bar';
const color = '#ff0000'; const color = '#ff0000';
const editTagCall = jest.fn();
const buildShlinkApiClient = () => Mock.of<ShlinkApiClient>({ editTag: editTagCall });
const colorGenerator = Mock.of<ColorGenerator>({ setColorForKey: jest.fn() });
const { reducer, editTag } = tagEditReducerCreator(buildShlinkApiClient, colorGenerator);
describe('reducer', () => { describe('reducer', () => {
it('returns loading on EDIT_TAG_START', () => { it('returns loading on EDIT_TAG_START', () => {
expect(reducer(undefined, Mock.of<EditTagAction>({ type: EDIT_TAG_START }))).toEqual({ expect(reducer(undefined, Mock.of<EditTagAction>({ type: editTag.pending.toString() }))).toEqual({
editing: true, editing: true,
edited: false, edited: false,
error: false, error: false,
@ -27,7 +23,7 @@ describe('tagEditReducer', () => {
}); });
it('returns error on EDIT_TAG_ERROR', () => { it('returns error on EDIT_TAG_ERROR', () => {
expect(reducer(undefined, Mock.of<EditTagAction>({ type: EDIT_TAG_ERROR }))).toEqual({ expect(reducer(undefined, Mock.of<EditTagAction>({ type: editTag.rejected.toString() }))).toEqual({
editing: false, editing: false,
edited: false, edited: false,
error: true, error: true,
@ -36,7 +32,7 @@ describe('tagEditReducer', () => {
it('returns tag names on EDIT_TAG', () => { it('returns tag names on EDIT_TAG', () => {
expect(reducer(undefined, { expect(reducer(undefined, {
type: EDIT_TAG, type: editTag.fulfilled.toString(),
payload: { oldName, newName, color }, payload: { oldName, newName, color },
})).toEqual({ })).toEqual({
editing: false, editing: false,
@ -51,7 +47,7 @@ describe('tagEditReducer', () => {
describe('tagEdited', () => { describe('tagEdited', () => {
it('returns action based on provided params', () => it('returns action based on provided params', () =>
expect(tagEdited({ oldName: 'foo', newName: 'bar', color: '#ff0000' })).toEqual({ expect(tagEdited({ oldName: 'foo', newName: 'bar', color: '#ff0000' })).toEqual({
type: TAG_EDITED, type: tagEdited.toString(),
payload: { payload: {
oldName: 'foo', oldName: 'foo',
newName: 'bar', newName: 'bar',
@ -61,56 +57,48 @@ describe('tagEditReducer', () => {
}); });
describe('editTag', () => { describe('editTag', () => {
const createApiClientMock = (result: Promise<any>) => Mock.of<ShlinkApiClient>({
editTag: jest.fn(async () => result),
});
const colorGenerator = Mock.of<ColorGenerator>({
setColorForKey: jest.fn(),
});
const dispatch = jest.fn(); const dispatch = jest.fn();
const getState = () => Mock.of<ShlinkState>(); const getState = () => Mock.of<ShlinkState>();
afterEach(jest.clearAllMocks); afterEach(jest.clearAllMocks);
it('calls API on success', async () => { it('calls API on success', async () => {
const apiClientMock = createApiClientMock(Promise.resolve()); editTagCall.mockResolvedValue(undefined);
const dispatchable = editTag(() => apiClientMock, colorGenerator)({ oldName, newName, color });
await dispatchable(dispatch, getState); await editTag({ oldName, newName, color })(dispatch, getState, {});
expect(apiClientMock.editTag).toHaveBeenCalledTimes(1); expect(editTagCall).toHaveBeenCalledTimes(1);
expect(apiClientMock.editTag).toHaveBeenCalledWith(oldName, newName); expect(editTagCall).toHaveBeenCalledWith(oldName, newName);
expect(colorGenerator.setColorForKey).toHaveBeenCalledTimes(1); expect(colorGenerator.setColorForKey).toHaveBeenCalledTimes(1);
expect(colorGenerator.setColorForKey).toHaveBeenCalledWith(newName, color); expect(colorGenerator.setColorForKey).toHaveBeenCalledWith(newName, color);
expect(dispatch).toHaveBeenCalledTimes(2); expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: EDIT_TAG_START }); expect(dispatch).toHaveBeenNthCalledWith(1, expect.objectContaining({ type: editTag.pending.toString() }));
expect(dispatch).toHaveBeenNthCalledWith(2, { expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: EDIT_TAG, type: editTag.fulfilled.toString(),
payload: { oldName, newName, color }, payload: { oldName, newName, color },
}); }));
}); });
it('throws on error', async () => { it('throws on error', async () => {
const error = 'Error'; const error = 'Error';
const apiClientMock = createApiClientMock(Promise.reject(error)); editTagCall.mockRejectedValue(error);
const dispatchable = editTag(() => apiClientMock, colorGenerator)({ oldName, newName, color });
try { try {
await dispatchable(dispatch, getState); await editTag({ oldName, newName, color })(dispatch, getState, {});
} catch (e) { } catch (e) {
expect(e).toEqual(error); expect(e).toEqual(error);
} }
expect(apiClientMock.editTag).toHaveBeenCalledTimes(1); expect(editTagCall).toHaveBeenCalledTimes(1);
expect(apiClientMock.editTag).toHaveBeenCalledWith(oldName, newName); expect(editTagCall).toHaveBeenCalledWith(oldName, newName);
expect(colorGenerator.setColorForKey).not.toHaveBeenCalled(); expect(colorGenerator.setColorForKey).not.toHaveBeenCalled();
expect(dispatch).toHaveBeenCalledTimes(2); expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: EDIT_TAG_START }); expect(dispatch).toHaveBeenNthCalledWith(1, expect.objectContaining({ type: editTag.pending.toString() }));
expect(dispatch).toHaveBeenNthCalledWith(2, { type: EDIT_TAG_ERROR }); expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({ type: editTag.rejected.toString() }));
}); });
}); });
}); });

View file

@ -9,10 +9,10 @@ import reducer, {
TagsList, TagsList,
} from '../../../src/tags/reducers/tagsList'; } from '../../../src/tags/reducers/tagsList';
import { TAG_DELETED } from '../../../src/tags/reducers/tagDelete'; import { TAG_DELETED } from '../../../src/tags/reducers/tagDelete';
import { TAG_EDITED } from '../../../src/tags/reducers/tagEdit';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
import { CREATE_SHORT_URL } from '../../../src/short-urls/reducers/shortUrlCreation'; import { CREATE_SHORT_URL } from '../../../src/short-urls/reducers/shortUrlCreation';
import { tagEdited } from '../../../src/tags/reducers/tagEdit';
describe('tagsListReducer', () => { describe('tagsListReducer', () => {
const state = (props: Partial<TagsList>) => Mock.of<TagsList>(props); const state = (props: Partial<TagsList>) => Mock.of<TagsList>(props);
@ -63,7 +63,7 @@ describe('tagsListReducer', () => {
expect(reducer( expect(reducer(
state({ tags, filteredTags: tags }), state({ tags, filteredTags: tags }),
{ {
type: TAG_EDITED, type: tagEdited.toString(),
payload: { oldName, newName }, payload: { oldName, newName },
} as any, } as any,
)).toEqual({ )).toEqual({