Migrated shortUrlDeletion reducer to RTK

This commit is contained in:
Alejandro Celaya 2022-11-06 13:06:55 +01:00
parent d468fb1efe
commit 830071278e
6 changed files with 73 additions and 82 deletions

View file

@ -3,7 +3,6 @@ import { combineReducers } from 'redux';
import { serversReducer } from '../servers/reducers/servers'; import { serversReducer } from '../servers/reducers/servers';
import selectedServerReducer from '../servers/reducers/selectedServer'; import selectedServerReducer from '../servers/reducers/selectedServer';
import shortUrlsListReducer from '../short-urls/reducers/shortUrlsList'; import shortUrlsListReducer from '../short-urls/reducers/shortUrlsList';
import shortUrlDeletionReducer from '../short-urls/reducers/shortUrlDeletion';
import shortUrlVisitsReducer from '../visits/reducers/shortUrlVisits'; import shortUrlVisitsReducer from '../visits/reducers/shortUrlVisits';
import tagVisitsReducer from '../visits/reducers/tagVisits'; import tagVisitsReducer from '../visits/reducers/tagVisits';
import domainVisitsReducer from '../visits/reducers/domainVisits'; import domainVisitsReducer from '../visits/reducers/domainVisits';
@ -24,7 +23,7 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
selectedServer: selectedServerReducer, selectedServer: selectedServerReducer,
shortUrlsList: shortUrlsListReducer, shortUrlsList: shortUrlsListReducer,
shortUrlCreationResult: container.shortUrlCreationReducer, shortUrlCreationResult: container.shortUrlCreationReducer,
shortUrlDeletion: shortUrlDeletionReducer, shortUrlDeletion: container.shortUrlDeletionReducer,
shortUrlEdition: container.shortUrlEditionReducer, shortUrlEdition: container.shortUrlEditionReducer,
shortUrlVisits: shortUrlVisitsReducer, shortUrlVisits: shortUrlVisitsReducer,
tagVisits: tagVisitsReducer, tagVisits: tagVisitsReducer,

View file

@ -1,20 +1,15 @@
import { PayloadAction } from '@reduxjs/toolkit'; import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Dispatch } from 'redux'; import { createAsyncThunk } from '../../utils/helpers/redux';
import { buildActionCreator, buildReducer } from '../../utils/helpers/redux';
import { GetState } from '../../container/types';
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 DELETE_SHORT_URL_START = 'shlink/deleteShortUrl/DELETE_SHORT_URL_START';
export const DELETE_SHORT_URL_ERROR = 'shlink/deleteShortUrl/DELETE_SHORT_URL_ERROR';
export const SHORT_URL_DELETED = 'shlink/deleteShortUrl/SHORT_URL_DELETED'; export const SHORT_URL_DELETED = 'shlink/deleteShortUrl/SHORT_URL_DELETED';
export const RESET_DELETE_SHORT_URL = 'shlink/deleteShortUrl/RESET_DELETE_SHORT_URL';
export interface ShortUrlDeletion { export interface ShortUrlDeletion {
shortCode: string; shortCode: string;
loading: boolean; loading: boolean;
deleted: boolean;
error: boolean; error: boolean;
errorData?: ProblemDetailsError; errorData?: ProblemDetailsError;
} }
@ -29,35 +24,38 @@ export type DeleteShortUrlAction = PayloadAction<DeleteShortUrl>;
const initialState: ShortUrlDeletion = { const initialState: ShortUrlDeletion = {
shortCode: '', shortCode: '',
loading: false, loading: false,
deleted: false,
error: false, error: false,
}; };
export default buildReducer<ShortUrlDeletion, DeleteShortUrlAction & ApiErrorAction>({ export const shortUrlDeletionReducerCreator = (buildShlinkApiClient: ShlinkApiClientBuilder) => {
[DELETE_SHORT_URL_START]: (state) => ({ ...state, loading: true, error: false }), const deleteShortUrl = createAsyncThunk(
[DELETE_SHORT_URL_ERROR]: (state, { errorData }) => ({ ...state, errorData, loading: false, error: true }), SHORT_URL_DELETED,
[SHORT_URL_DELETED]: (state, { payload }) => ( async ({ shortCode, domain }: DeleteShortUrl, { getState }): Promise<DeleteShortUrl> => {
{ ...state, shortCode: payload.shortCode, loading: false, error: false }
),
[RESET_DELETE_SHORT_URL]: () => initialState,
}, initialState);
export const deleteShortUrl = (buildShlinkApiClient: ShlinkApiClientBuilder) => (
{ shortCode, domain }: DeleteShortUrl,
) => async (dispatch: Dispatch, getState: GetState) => {
dispatch({ type: DELETE_SHORT_URL_START });
const { deleteShortUrl: shlinkDeleteShortUrl } = buildShlinkApiClient(getState); const { deleteShortUrl: shlinkDeleteShortUrl } = buildShlinkApiClient(getState);
try {
await shlinkDeleteShortUrl(shortCode, domain); await shlinkDeleteShortUrl(shortCode, domain);
dispatch<DeleteShortUrlAction>({ return { shortCode, domain };
type: SHORT_URL_DELETED, },
payload: { shortCode, domain }, );
const { actions, reducer } = createSlice({
name: 'shortUrlDeletion',
initialState,
reducers: {
resetDeleteShortUrl: () => initialState,
},
extraReducers: (builder) => {
builder.addCase(deleteShortUrl.pending, (state) => ({ ...state, loading: true, error: false, deleted: false }));
builder.addCase(deleteShortUrl.rejected, (state, { error }) => (
{ ...state, errorData: parseApiError(error), loading: false, error: true, deleted: false }
));
builder.addCase(deleteShortUrl.fulfilled, (state, { payload }) => (
{ ...state, shortCode: payload.shortCode, loading: false, error: false, deleted: true }
));
},
}); });
} catch (e: any) {
dispatch<ApiErrorAction>({ type: DELETE_SHORT_URL_ERROR, errorData: parseApiError(e) });
throw e; const { resetDeleteShortUrl } = actions;
}
return { reducer, deleteShortUrl, resetDeleteShortUrl };
}; };
export const resetDeleteShortUrl = buildActionCreator(RESET_DELETE_SHORT_URL);

View file

@ -44,8 +44,7 @@ export default buildReducer<ShortUrlsList, ListShortUrlsCombinedAction>({
[LIST_SHORT_URLS_START]: (state) => ({ ...state, loading: true, error: false }), [LIST_SHORT_URLS_START]: (state) => ({ ...state, loading: true, error: false }),
[LIST_SHORT_URLS_ERROR]: () => ({ loading: false, error: true }), [LIST_SHORT_URLS_ERROR]: () => ({ loading: false, error: true }),
[LIST_SHORT_URLS]: (_, { shortUrls }) => ({ loading: false, error: false, shortUrls }), [LIST_SHORT_URLS]: (_, { shortUrls }) => ({ loading: false, error: false, shortUrls }),
// [`${SHORT_URL_DELETED}/fulfilled`]: pipe( // TODO Do not hardcode action type here [`${SHORT_URL_DELETED}/fulfilled`]: pipe( // TODO Do not hardcode action type here
[SHORT_URL_DELETED]: pipe(
(state: ShortUrlsList, { payload }: DeleteShortUrlAction) => (!state.shortUrls ? state : assocPath( (state: ShortUrlsList, { payload }: DeleteShortUrlAction) => (!state.shortUrls ? state : assocPath(
['shortUrls', 'data'], ['shortUrls', 'data'],
reject<ShortUrl, ShortUrl[]>((shortUrl) => reject<ShortUrl, ShortUrl[]>((shortUrl) =>

View file

@ -9,7 +9,7 @@ import { DeleteShortUrlModal } from '../helpers/DeleteShortUrlModal';
import { CreateShortUrlResult } from '../helpers/CreateShortUrlResult'; import { CreateShortUrlResult } from '../helpers/CreateShortUrlResult';
import { listShortUrls } from '../reducers/shortUrlsList'; import { listShortUrls } from '../reducers/shortUrlsList';
import { shortUrlCreationReducerCreator } from '../reducers/shortUrlCreation'; import { shortUrlCreationReducerCreator } from '../reducers/shortUrlCreation';
import { deleteShortUrl, resetDeleteShortUrl } from '../reducers/shortUrlDeletion'; import { shortUrlDeletionReducerCreator } from '../reducers/shortUrlDeletion';
import { shortUrlEditionReducerCreator } from '../reducers/shortUrlEdition'; import { shortUrlEditionReducerCreator } from '../reducers/shortUrlEdition';
import { ConnectDecorator } from '../../container/types'; import { ConnectDecorator } from '../../container/types';
import { ShortUrlsTable } from '../ShortUrlsTable'; import { ShortUrlsTable } from '../ShortUrlsTable';
@ -63,14 +63,17 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.serviceFactory('shortUrlEditionReducerCreator', shortUrlEditionReducerCreator, 'buildShlinkApiClient'); bottle.serviceFactory('shortUrlEditionReducerCreator', shortUrlEditionReducerCreator, 'buildShlinkApiClient');
bottle.serviceFactory('shortUrlEditionReducer', prop('reducer'), 'shortUrlEditionReducerCreator'); bottle.serviceFactory('shortUrlEditionReducer', prop('reducer'), 'shortUrlEditionReducerCreator');
bottle.serviceFactory('shortUrlDeletionReducerCreator', shortUrlDeletionReducerCreator, 'buildShlinkApiClient');
bottle.serviceFactory('shortUrlDeletionReducer', prop('reducer'), 'shortUrlDeletionReducerCreator');
// Actions // Actions
bottle.serviceFactory('listShortUrls', listShortUrls, 'buildShlinkApiClient'); bottle.serviceFactory('listShortUrls', listShortUrls, 'buildShlinkApiClient');
bottle.serviceFactory('createShortUrl', prop('createShortUrl'), 'shortUrlCreationReducerCreator'); bottle.serviceFactory('createShortUrl', prop('createShortUrl'), 'shortUrlCreationReducerCreator');
bottle.serviceFactory('resetCreateShortUrl', prop('resetCreateShortUrl'), 'shortUrlCreationReducerCreator'); bottle.serviceFactory('resetCreateShortUrl', prop('resetCreateShortUrl'), 'shortUrlCreationReducerCreator');
bottle.serviceFactory('deleteShortUrl', deleteShortUrl, 'buildShlinkApiClient'); bottle.serviceFactory('deleteShortUrl', prop('deleteShortUrl'), 'shortUrlDeletionReducerCreator');
bottle.serviceFactory('resetDeleteShortUrl', () => resetDeleteShortUrl); bottle.serviceFactory('resetDeleteShortUrl', prop('resetDeleteShortUrl'), 'shortUrlDeletionReducerCreator');
bottle.serviceFactory('getShortUrlDetail', getShortUrlDetail, 'buildShlinkApiClient'); bottle.serviceFactory('getShortUrlDetail', getShortUrlDetail, 'buildShlinkApiClient');

View file

@ -1,48 +1,52 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import reducer, { import { shortUrlDeletionReducerCreator } from '../../../src/short-urls/reducers/shortUrlDeletion';
DELETE_SHORT_URL_ERROR,
DELETE_SHORT_URL_START,
RESET_DELETE_SHORT_URL,
SHORT_URL_DELETED,
resetDeleteShortUrl,
deleteShortUrl,
} from '../../../src/short-urls/reducers/shortUrlDeletion';
import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient'; import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ProblemDetailsError } from '../../../src/api/types/errors'; import { ProblemDetailsError } from '../../../src/api/types/errors';
describe('shortUrlDeletionReducer', () => { describe('shortUrlDeletionReducer', () => {
const deleteShortUrlCall = jest.fn();
const buildShlinkApiClient = () => Mock.of<ShlinkApiClient>({ deleteShortUrl: deleteShortUrlCall });
const { reducer, resetDeleteShortUrl, deleteShortUrl } = shortUrlDeletionReducerCreator(buildShlinkApiClient);
beforeEach(jest.clearAllMocks);
describe('reducer', () => { describe('reducer', () => {
it('returns loading on DELETE_SHORT_URL_START', () => it('returns loading on DELETE_SHORT_URL_START', () =>
expect(reducer(undefined, { type: DELETE_SHORT_URL_START } as any)).toEqual({ expect(reducer(undefined, { type: deleteShortUrl.pending.toString() } as any)).toEqual({
shortCode: '', shortCode: '',
loading: true, loading: true,
error: false, error: false,
deleted: false,
})); }));
it('returns default on RESET_DELETE_SHORT_URL', () => it('returns default on RESET_DELETE_SHORT_URL', () =>
expect(reducer(undefined, { type: RESET_DELETE_SHORT_URL } as any)).toEqual({ expect(reducer(undefined, { type: resetDeleteShortUrl.toString() } as any)).toEqual({
shortCode: '', shortCode: '',
loading: false, loading: false,
error: false, error: false,
deleted: false,
})); }));
it('returns shortCode on SHORT_URL_DELETED', () => it('returns shortCode on SHORT_URL_DELETED', () =>
expect(reducer(undefined, { expect(reducer(undefined, {
type: SHORT_URL_DELETED, type: deleteShortUrl.fulfilled.toString(),
payload: { shortCode: 'foo' }, payload: { shortCode: 'foo' },
} as any)).toEqual({ } as any)).toEqual({
shortCode: 'foo', shortCode: 'foo',
loading: false, loading: false,
error: false, error: false,
deleted: true,
})); }));
it('returns errorData on DELETE_SHORT_URL_ERROR', () => { it('returns errorData on DELETE_SHORT_URL_ERROR', () => {
const errorData = Mock.of<ProblemDetailsError>({ type: 'bar' }); const errorData = Mock.of<ProblemDetailsError>({ type: 'bar' });
const error = { response: { data: errorData } };
expect(reducer(undefined, { type: DELETE_SHORT_URL_ERROR, errorData } as any)).toEqual({ expect(reducer(undefined, { type: deleteShortUrl.rejected.toString(), error } as any)).toEqual({
shortCode: '', shortCode: '',
loading: false, loading: false,
error: true, error: true,
deleted: false,
errorData, errorData,
}); });
}); });
@ -50,59 +54,47 @@ describe('shortUrlDeletionReducer', () => {
describe('resetDeleteShortUrl', () => { describe('resetDeleteShortUrl', () => {
it('returns expected action', () => it('returns expected action', () =>
expect(resetDeleteShortUrl()).toEqual({ type: RESET_DELETE_SHORT_URL })); expect(resetDeleteShortUrl()).toEqual({ type: resetDeleteShortUrl.toString() }));
}); });
describe('deleteShortUrl', () => { describe('deleteShortUrl', () => {
const dispatch = jest.fn(); const dispatch = jest.fn();
const getState = jest.fn().mockReturnValue({ selectedServer: {} }); const getState = jest.fn().mockReturnValue({ selectedServer: {} });
afterEach(() => {
dispatch.mockReset();
getState.mockClear();
});
it.each( it.each(
[[undefined], [null], ['example.com']], [[undefined], [null], ['example.com']],
)('dispatches proper actions if API client request succeeds', async (domain) => { )('dispatches proper actions if API client request succeeds', async (domain) => {
const apiClientMock = Mock.of<ShlinkApiClient>({
deleteShortUrl: jest.fn(() => ''),
});
const shortCode = 'abc123'; const shortCode = 'abc123';
await deleteShortUrl(() => apiClientMock)({ shortCode, domain })(dispatch, getState); await deleteShortUrl({ shortCode, domain })(dispatch, getState, {});
expect(dispatch).toHaveBeenCalledTimes(2); expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: DELETE_SHORT_URL_START }); expect(dispatch).toHaveBeenNthCalledWith(1, expect.objectContaining({ type: deleteShortUrl.pending.toString() }));
expect(dispatch).toHaveBeenNthCalledWith(2, { expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: SHORT_URL_DELETED, type: deleteShortUrl.fulfilled.toString(),
payload: { shortCode, domain }, payload: { shortCode, domain },
}); }));
expect(apiClientMock.deleteShortUrl).toHaveBeenCalledTimes(1); expect(deleteShortUrlCall).toHaveBeenCalledTimes(1);
expect(apiClientMock.deleteShortUrl).toHaveBeenCalledWith(shortCode, domain); expect(deleteShortUrlCall).toHaveBeenCalledWith(shortCode, domain);
}); });
it('dispatches proper actions if API client request fails', async () => { it('dispatches proper actions if API client request fails', async () => {
const data = { foo: 'bar' }; const data = { foo: 'bar' };
const error = { response: { data } };
const apiClientMock = Mock.of<ShlinkApiClient>({
deleteShortUrl: jest.fn(async () => Promise.reject(error)),
});
const shortCode = 'abc123'; const shortCode = 'abc123';
try { deleteShortUrlCall.mockRejectedValue({ response: { data } });
await deleteShortUrl(() => apiClientMock)({ shortCode })(dispatch, getState);
} catch (e) { await deleteShortUrl({ shortCode })(dispatch, getState, {});
expect(e).toEqual(error);
}
expect(dispatch).toHaveBeenCalledTimes(2); expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: DELETE_SHORT_URL_START }); expect(dispatch).toHaveBeenNthCalledWith(1, expect.objectContaining({ type: deleteShortUrl.pending.toString() }));
expect(dispatch).toHaveBeenNthCalledWith(2, { type: DELETE_SHORT_URL_ERROR, errorData: data }); expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: deleteShortUrl.rejected.toString(),
}));
expect(apiClientMock.deleteShortUrl).toHaveBeenCalledTimes(1); expect(deleteShortUrlCall).toHaveBeenCalledTimes(1);
expect(apiClientMock.deleteShortUrl).toHaveBeenCalledWith(shortCode, undefined); expect(deleteShortUrlCall).toHaveBeenCalledWith(shortCode, undefined);
}); });
}); });
}); });

View file

@ -52,7 +52,7 @@ describe('shortUrlsListReducer', () => {
error: false, error: false,
}; };
expect(reducer(state, { type: SHORT_URL_DELETED, payload: { shortCode } } as any)).toEqual({ expect(reducer(state, { type: `${SHORT_URL_DELETED}/fulfilled`, payload: { shortCode } } as any)).toEqual({
shortUrls: { shortUrls: {
data: [{ shortCode, domain: 'example.com' }, { shortCode: 'foo' }], data: [{ shortCode, domain: 'example.com' }, { shortCode: 'foo' }],
pagination: { totalItems: 9 }, pagination: { totalItems: 9 },