Migrated short URL detail reducer to RTK

This commit is contained in:
Alejandro Celaya 2022-11-06 19:32:02 +01:00
parent f93bb88d35
commit f803941fe4
4 changed files with 73 additions and 59 deletions

View file

@ -8,7 +8,6 @@ import tagVisitsReducer from '../visits/reducers/tagVisits';
import domainVisitsReducer from '../visits/reducers/domainVisits'; import domainVisitsReducer from '../visits/reducers/domainVisits';
import orphanVisitsReducer from '../visits/reducers/orphanVisits'; import orphanVisitsReducer from '../visits/reducers/orphanVisits';
import nonOrphanVisitsReducer from '../visits/reducers/nonOrphanVisits'; import nonOrphanVisitsReducer from '../visits/reducers/nonOrphanVisits';
import shortUrlDetailReducer from '../short-urls/reducers/shortUrlDetail';
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 tagEditReducer from '../tags/reducers/tagEdit';
@ -25,12 +24,12 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
shortUrlCreationResult: container.shortUrlCreationReducer, shortUrlCreationResult: container.shortUrlCreationReducer,
shortUrlDeletion: container.shortUrlDeletionReducer, shortUrlDeletion: container.shortUrlDeletionReducer,
shortUrlEdition: container.shortUrlEditionReducer, shortUrlEdition: container.shortUrlEditionReducer,
shortUrlDetail: container.shortUrlDetailReducer,
shortUrlVisits: shortUrlVisitsReducer, shortUrlVisits: shortUrlVisitsReducer,
tagVisits: tagVisitsReducer, tagVisits: tagVisitsReducer,
domainVisits: domainVisitsReducer, domainVisits: domainVisitsReducer,
orphanVisits: orphanVisitsReducer, orphanVisits: orphanVisitsReducer,
nonOrphanVisits: nonOrphanVisitsReducer, nonOrphanVisits: nonOrphanVisitsReducer,
shortUrlDetail: shortUrlDetailReducer,
tagsList: tagsListReducer, tagsList: tagsListReducer,
tagDelete: tagDeleteReducer, tagDelete: tagDeleteReducer,
tagEdit: tagEditReducer, tagEdit: tagEditReducer,

View file

@ -1,17 +1,12 @@
import { PayloadAction } from '@reduxjs/toolkit'; import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Dispatch } from 'redux';
import { ShortUrl, ShortUrlIdentifier } from '../data'; import { ShortUrl, ShortUrlIdentifier } from '../data';
import { buildReducer } from '../../utils/helpers/redux'; import { createAsyncThunk } from '../../utils/helpers/redux';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
import { GetState } from '../../container/types';
import { shortUrlMatches } from '../helpers'; import { shortUrlMatches } from '../helpers';
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 GET_SHORT_URL_DETAIL_START = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL_START'; const GET_SHORT_URL_DETAIL = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL';
export const GET_SHORT_URL_DETAIL_ERROR = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL_ERROR';
export const GET_SHORT_URL_DETAIL = 'shlink/shortUrlDetail/GET_SHORT_URL_DETAIL';
export interface ShortUrlDetail { export interface ShortUrlDetail {
shortUrl?: ShortUrl; shortUrl?: ShortUrl;
@ -27,25 +22,29 @@ const initialState: ShortUrlDetail = {
error: false, error: false,
}; };
export default buildReducer<ShortUrlDetail, ShortUrlDetailAction & ApiErrorAction>({ export const shortUrlDetailReducerCreator = (buildShlinkApiClient: ShlinkApiClientBuilder) => {
[GET_SHORT_URL_DETAIL_START]: () => ({ loading: true, error: false }), const getShortUrlDetail = createAsyncThunk(
[GET_SHORT_URL_DETAIL_ERROR]: (_, { errorData }) => ({ loading: false, error: true, errorData }), GET_SHORT_URL_DETAIL,
[GET_SHORT_URL_DETAIL]: (_, { payload: shortUrl }) => ({ shortUrl, ...initialState }), async ({ shortCode, domain }: ShortUrlIdentifier, { getState }): Promise<ShortUrl> => {
}, initialState);
export const getShortUrlDetail = (buildShlinkApiClient: ShlinkApiClientBuilder) => (
{ shortCode, domain }: ShortUrlIdentifier,
) => async (dispatch: Dispatch, getState: GetState) => {
dispatch({ type: GET_SHORT_URL_DETAIL_START });
try {
const { shortUrlsList } = getState(); const { shortUrlsList } = getState();
const payload = shortUrlsList?.shortUrls?.data.find( const alreadyLoaded = shortUrlsList?.shortUrls?.data.find((url) => shortUrlMatches(url, shortCode, domain));
(url) => shortUrlMatches(url, shortCode, domain),
) ?? await buildShlinkApiClient(getState).getShortUrl(shortCode, domain);
dispatch<ShortUrlDetailAction>({ payload, type: GET_SHORT_URL_DETAIL }); return alreadyLoaded ?? await buildShlinkApiClient(getState).getShortUrl(shortCode, domain);
} catch (e: any) { },
dispatch<ApiErrorAction>({ type: GET_SHORT_URL_DETAIL_ERROR, errorData: parseApiError(e) }); );
}
const { reducer } = createSlice({
name: 'shortUrlDetailReducer',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(getShortUrlDetail.pending, () => ({ loading: true, error: false }));
builder.addCase(getShortUrlDetail.rejected, (_, { error }) => (
{ loading: false, error: true, errorData: parseApiError(error) }
));
builder.addCase(getShortUrlDetail.fulfilled, (_, { payload: shortUrl }) => ({ ...initialState, shortUrl }));
},
});
return { reducer, getShortUrlDetail };
}; };

View file

@ -11,12 +11,12 @@ import { listShortUrls } from '../reducers/shortUrlsList';
import { shortUrlCreationReducerCreator } from '../reducers/shortUrlCreation'; import { shortUrlCreationReducerCreator } from '../reducers/shortUrlCreation';
import { shortUrlDeletionReducerCreator } from '../reducers/shortUrlDeletion'; import { shortUrlDeletionReducerCreator } from '../reducers/shortUrlDeletion';
import { shortUrlEditionReducerCreator } from '../reducers/shortUrlEdition'; import { shortUrlEditionReducerCreator } from '../reducers/shortUrlEdition';
import { shortUrlDetailReducerCreator } from '../reducers/shortUrlDetail';
import { ConnectDecorator } from '../../container/types'; import { ConnectDecorator } from '../../container/types';
import { ShortUrlsTable } from '../ShortUrlsTable'; import { ShortUrlsTable } from '../ShortUrlsTable';
import { QrCodeModal } from '../helpers/QrCodeModal';
import { ShortUrlForm } from '../ShortUrlForm'; import { ShortUrlForm } from '../ShortUrlForm';
import { EditShortUrl } from '../EditShortUrl'; import { EditShortUrl } from '../EditShortUrl';
import { getShortUrlDetail } from '../reducers/shortUrlDetail'; import { QrCodeModal } from '../helpers/QrCodeModal';
import { ExportShortUrlsBtn } from '../helpers/ExportShortUrlsBtn'; import { ExportShortUrlsBtn } from '../helpers/ExportShortUrlsBtn';
const provideServices = (bottle: Bottle, connect: ConnectDecorator) => { const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
@ -66,6 +66,9 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.serviceFactory('shortUrlDeletionReducerCreator', shortUrlDeletionReducerCreator, 'buildShlinkApiClient'); bottle.serviceFactory('shortUrlDeletionReducerCreator', shortUrlDeletionReducerCreator, 'buildShlinkApiClient');
bottle.serviceFactory('shortUrlDeletionReducer', prop('reducer'), 'shortUrlDeletionReducerCreator'); bottle.serviceFactory('shortUrlDeletionReducer', prop('reducer'), 'shortUrlDeletionReducerCreator');
bottle.serviceFactory('shortUrlDetailReducerCreator', shortUrlDetailReducerCreator, 'buildShlinkApiClient');
bottle.serviceFactory('shortUrlDetailReducer', prop('reducer'), 'shortUrlDetailReducerCreator');
// Actions // Actions
bottle.serviceFactory('listShortUrls', listShortUrls, 'buildShlinkApiClient'); bottle.serviceFactory('listShortUrls', listShortUrls, 'buildShlinkApiClient');
@ -75,7 +78,7 @@ const provideServices = (bottle: Bottle, connect: ConnectDecorator) => {
bottle.serviceFactory('deleteShortUrl', prop('deleteShortUrl'), 'shortUrlDeletionReducerCreator'); bottle.serviceFactory('deleteShortUrl', prop('deleteShortUrl'), 'shortUrlDeletionReducerCreator');
bottle.serviceFactory('resetDeleteShortUrl', prop('resetDeleteShortUrl'), 'shortUrlDeletionReducerCreator'); bottle.serviceFactory('resetDeleteShortUrl', prop('resetDeleteShortUrl'), 'shortUrlDeletionReducerCreator');
bottle.serviceFactory('getShortUrlDetail', getShortUrlDetail, 'buildShlinkApiClient'); bottle.serviceFactory('getShortUrlDetail', prop('getShortUrlDetail'), 'shortUrlDetailReducerCreator');
bottle.serviceFactory('editShortUrl', prop('editShortUrl'), 'shortUrlEditionReducerCreator'); bottle.serviceFactory('editShortUrl', prop('editShortUrl'), 'shortUrlEditionReducerCreator');
}; };

View file

@ -1,31 +1,29 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import reducer, { import { ShortUrlDetailAction, shortUrlDetailReducerCreator } from '../../../src/short-urls/reducers/shortUrlDetail';
getShortUrlDetail,
GET_SHORT_URL_DETAIL_START,
GET_SHORT_URL_DETAIL_ERROR,
GET_SHORT_URL_DETAIL,
ShortUrlDetailAction,
} from '../../../src/short-urls/reducers/shortUrlDetail';
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient'; import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
import { ShortUrlsList } from '../../../src/short-urls/reducers/shortUrlsList'; import { ShortUrlsList } from '../../../src/short-urls/reducers/shortUrlsList';
describe('shortUrlDetailReducer', () => { describe('shortUrlDetailReducer', () => {
const getShortUrlCall = jest.fn();
const buildShlinkApiClient = () => Mock.of<ShlinkApiClient>({ getShortUrl: getShortUrlCall });
const { reducer, getShortUrlDetail } = shortUrlDetailReducerCreator(buildShlinkApiClient);
beforeEach(jest.clearAllMocks); beforeEach(jest.clearAllMocks);
describe('reducer', () => { describe('reducer', () => {
const action = (type: string) => Mock.of<ShortUrlDetailAction>({ type }); const action = (type: string) => Mock.of<ShortUrlDetailAction>({ type });
it('returns loading on GET_SHORT_URL_DETAIL_START', () => { it('returns loading on GET_SHORT_URL_DETAIL_START', () => {
const state = reducer({ loading: false, error: false }, action(GET_SHORT_URL_DETAIL_START)); const state = reducer({ loading: false, error: false }, action(getShortUrlDetail.pending.toString()));
const { loading } = state; const { loading } = state;
expect(loading).toEqual(true); expect(loading).toEqual(true);
}); });
it('stops loading and returns error on GET_SHORT_URL_DETAIL_ERROR', () => { it('stops loading and returns error on GET_SHORT_URL_DETAIL_ERROR', () => {
const state = reducer({ loading: true, error: false }, action(GET_SHORT_URL_DETAIL_ERROR)); const state = reducer({ loading: true, error: false }, action(getShortUrlDetail.rejected.toString()));
const { loading, error } = state; const { loading, error } = state;
expect(loading).toEqual(false); expect(loading).toEqual(false);
@ -34,7 +32,10 @@ describe('shortUrlDetailReducer', () => {
it('return short URL on GET_SHORT_URL_DETAIL', () => { it('return short URL on GET_SHORT_URL_DETAIL', () => {
const actionShortUrl = Mock.of<ShortUrl>({ longUrl: 'foo', shortCode: 'bar' }); const actionShortUrl = Mock.of<ShortUrl>({ longUrl: 'foo', shortCode: 'bar' });
const state = reducer({ loading: true, error: false }, { type: GET_SHORT_URL_DETAIL, payload: actionShortUrl }); const state = reducer(
{ loading: true, error: false },
{ type: getShortUrlDetail.fulfilled.toString(), payload: actionShortUrl },
);
const { loading, error, shortUrl } = state; const { loading, error, shortUrl } = state;
expect(loading).toEqual(false); expect(loading).toEqual(false);
@ -44,21 +45,22 @@ describe('shortUrlDetailReducer', () => {
}); });
describe('getShortUrlDetail', () => { describe('getShortUrlDetail', () => {
const buildApiClientMock = (returned: Promise<ShortUrl>) => Mock.of<ShlinkApiClient>({
getShortUrl: jest.fn(async () => returned),
});
const dispatchMock = jest.fn(); const dispatchMock = jest.fn();
const buildGetState = (shortUrlsList?: ShortUrlsList) => () => Mock.of<ShlinkState>({ shortUrlsList }); const buildGetState = (shortUrlsList?: ShortUrlsList) => () => Mock.of<ShlinkState>({ shortUrlsList });
it('dispatches start and error when promise is rejected', async () => { it('dispatches start and error when promise is rejected', async () => {
const ShlinkApiClient = buildApiClientMock(Promise.reject({})); getShortUrlCall.mockRejectedValue({});
await getShortUrlDetail(() => ShlinkApiClient)({ shortCode: 'abc123', domain: '' })(dispatchMock, buildGetState()); await getShortUrlDetail({ shortCode: 'abc123', domain: '' })(dispatchMock, buildGetState(), {});
expect(dispatchMock).toHaveBeenCalledTimes(2); expect(dispatchMock).toHaveBeenCalledTimes(2);
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_SHORT_URL_DETAIL_START }); expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
expect(dispatchMock).toHaveBeenNthCalledWith(2, { type: GET_SHORT_URL_DETAIL_ERROR }); type: getShortUrlDetail.pending.toString(),
expect(ShlinkApiClient.getShortUrl).toHaveBeenCalledTimes(1); }));
expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: getShortUrlDetail.rejected.toString(),
}));
expect(getShortUrlCall).toHaveBeenCalledTimes(1);
}); });
it.each([ it.each([
@ -78,33 +80,44 @@ describe('shortUrlDetailReducer', () => {
], ],
])('performs API call when short URL is not found in local state', async (shortUrlsList?: ShortUrlsList) => { ])('performs API call when short URL is not found in local state', async (shortUrlsList?: ShortUrlsList) => {
const resolvedShortUrl = Mock.of<ShortUrl>({ longUrl: 'foo', shortCode: 'abc123' }); const resolvedShortUrl = Mock.of<ShortUrl>({ longUrl: 'foo', shortCode: 'abc123' });
const ShlinkApiClient = buildApiClientMock(Promise.resolve(resolvedShortUrl)); getShortUrlCall.mockResolvedValue(resolvedShortUrl);
await getShortUrlDetail(() => ShlinkApiClient)({ shortCode: 'abc123', domain: '' })(dispatchMock, buildGetState(shortUrlsList)); await getShortUrlDetail({ shortCode: 'abc123', domain: '' })(dispatchMock, buildGetState(shortUrlsList), {});
expect(dispatchMock).toHaveBeenCalledTimes(2); expect(dispatchMock).toHaveBeenCalledTimes(2);
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_SHORT_URL_DETAIL_START }); expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
expect(dispatchMock).toHaveBeenNthCalledWith(2, { type: GET_SHORT_URL_DETAIL, payload: resolvedShortUrl }); type: getShortUrlDetail.pending.toString(),
expect(ShlinkApiClient.getShortUrl).toHaveBeenCalledTimes(1); }));
expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: getShortUrlDetail.fulfilled.toString(),
payload: resolvedShortUrl,
}));
expect(getShortUrlCall).toHaveBeenCalledTimes(1);
}); });
it('avoids API calls when short URL is found in local state', async () => { it('avoids API calls when short URL is found in local state', async () => {
const foundShortUrl = Mock.of<ShortUrl>({ longUrl: 'foo', shortCode: 'abc123' }); const foundShortUrl = Mock.of<ShortUrl>({ longUrl: 'foo', shortCode: 'abc123' });
const ShlinkApiClient = buildApiClientMock(Promise.resolve(Mock.all<ShortUrl>())); getShortUrlCall.mockResolvedValue(Mock.all<ShortUrl>());
await getShortUrlDetail(() => ShlinkApiClient)(foundShortUrl)( await getShortUrlDetail(foundShortUrl)(
dispatchMock, dispatchMock,
buildGetState(Mock.of<ShortUrlsList>({ buildGetState(Mock.of<ShortUrlsList>({
shortUrls: { shortUrls: {
data: [foundShortUrl], data: [foundShortUrl],
}, },
})), })),
{},
); );
expect(dispatchMock).toHaveBeenCalledTimes(2); expect(dispatchMock).toHaveBeenCalledTimes(2);
expect(dispatchMock).toHaveBeenNthCalledWith(1, { type: GET_SHORT_URL_DETAIL_START }); expect(dispatchMock).toHaveBeenNthCalledWith(1, expect.objectContaining({
expect(dispatchMock).toHaveBeenNthCalledWith(2, { type: GET_SHORT_URL_DETAIL, payload: foundShortUrl }); type: getShortUrlDetail.pending.toString(),
expect(ShlinkApiClient.getShortUrl).not.toHaveBeenCalled(); }));
expect(dispatchMock).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: getShortUrlDetail.fulfilled.toString(),
payload: foundShortUrl,
}));
expect(getShortUrlCall).not.toHaveBeenCalled();
}); });
}); });
}); });