Merge pull request #730 from acelaya-forks/feature/more-rtk

Feature/more rtk
This commit is contained in:
Alejandro Celaya 2022-11-07 22:49:33 +01:00 committed by GitHub
commit b9e02cf344
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 223 additions and 228 deletions

View file

@ -9,8 +9,6 @@ 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 tagsListReducer from '../tags/reducers/tagsList'; import tagsListReducer from '../tags/reducers/tagsList';
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';
@ -31,8 +29,8 @@ export default (container: IContainer) => combineReducers<ShlinkState>({
orphanVisits: orphanVisitsReducer, orphanVisits: orphanVisitsReducer,
nonOrphanVisits: nonOrphanVisitsReducer, nonOrphanVisits: nonOrphanVisitsReducer,
tagsList: tagsListReducer, tagsList: tagsListReducer,
tagDelete: tagDeleteReducer, tagDelete: container.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,7 +1,7 @@
import { assoc, assocPath, last, pipe, reject } from 'ramda'; import { assoc, assocPath, last, pipe, reject } from 'ramda';
import { Action, Dispatch } from 'redux'; import { Action, Dispatch } from 'redux';
import { shortUrlMatches } from '../helpers'; import { shortUrlMatches } from '../helpers';
import { CREATE_VISITS, CreateVisitsAction } from '../../visits/reducers/visitCreation'; import { createNewVisits, CreateVisitsAction } from '../../visits/reducers/visitCreation';
import { buildReducer } from '../../utils/helpers/redux'; import { buildReducer } from '../../utils/helpers/redux';
import { GetState } from '../../container/types'; import { GetState } from '../../container/types';
import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder'; import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilder';
@ -57,7 +57,7 @@ export default buildReducer<ShortUrlsList, ListShortUrlsCombinedAction>({
state, state,
)), )),
), ),
[CREATE_VISITS]: (state, { payload }) => assocPath( [createNewVisits.toString()]: (state, { payload }) => assocPath(
['shortUrls', 'data'], ['shortUrls', 'data'],
state.shortUrls?.data?.map( state.shortUrls?.data?.map(
(currentShortUrl) => { (currentShortUrl) => {

View file

@ -13,15 +13,14 @@ interface DeleteTagConfirmModalProps extends TagModalProps {
export const DeleteTagConfirmModal = ( export const DeleteTagConfirmModal = (
{ tag, toggle, isOpen, deleteTag, tagDelete, tagDeleted }: DeleteTagConfirmModalProps, { tag, toggle, isOpen, deleteTag, tagDelete, tagDeleted }: DeleteTagConfirmModalProps,
) => { ) => {
const { deleting, error, errorData } = tagDelete; const { deleting, error, deleted, errorData } = tagDelete;
const doDelete = async () => { const doDelete = async () => {
await deleteTag(tag); await deleteTag(tag);
tagDeleted(tag);
toggle(); toggle();
}; };
return ( return (
<Modal toggle={toggle} isOpen={isOpen} centered> <Modal toggle={toggle} isOpen={isOpen} centered onClosed={() => deleted && tagDeleted(tag)}>
<ModalHeader toggle={toggle} className="text-danger">Delete tag</ModalHeader> <ModalHeader toggle={toggle} className="text-danger">Delete tag</ModalHeader>
<ModalBody> <ModalBody>
Are you sure you want to delete tag <b>{tag}</b>? Are you sure you want to delete tag <b>{tag}</b>?

View file

@ -1,3 +1,4 @@
import { pipe } from 'ramda';
import { useState } from 'react'; import { useState } from 'react';
import { Button, Input, Modal, ModalBody, ModalFooter, ModalHeader, Popover, InputGroup } from 'reactstrap'; import { Button, Input, Modal, ModalBody, ModalFooter, ModalHeader, Popover, InputGroup } from 'reactstrap';
import { HexColorPicker } from 'react-colorful'; import { HexColorPicker } from 'react-colorful';
@ -7,15 +8,15 @@ import { useToggle } from '../../utils/helpers/hooks';
import { handleEventPreventingDefault } from '../../utils/utils'; import { handleEventPreventingDefault } from '../../utils/utils';
import { ColorGenerator } from '../../utils/services/ColorGenerator'; import { ColorGenerator } from '../../utils/services/ColorGenerator';
import { TagModalProps } from '../data'; import { TagModalProps } from '../data';
import { TagEdition } from '../reducers/tagEdit'; import { EditTag, TagEdition } from '../reducers/tagEdit';
import { Result } from '../../utils/Result'; import { Result } from '../../utils/Result';
import { ShlinkApiError } from '../../api/ShlinkApiError'; import { ShlinkApiError } from '../../api/ShlinkApiError';
import './EditTagModal.scss'; import './EditTagModal.scss';
interface EditTagModalProps extends TagModalProps { interface EditTagModalProps extends TagModalProps {
tagEdit: TagEdition; tagEdit: TagEdition;
editTag: (oldName: string, newName: string, color: string) => Promise<void>; editTag: (editTag: EditTag) => Promise<void>;
tagEdited: (oldName: string, newName: string, color: string) => void; tagEdited: (tagEdited: EditTag) => void;
} }
export const EditTagModal = ({ getColorForKey }: ColorGenerator) => ( export const EditTagModal = ({ getColorForKey }: ColorGenerator) => (
@ -24,16 +25,16 @@ export const EditTagModal = ({ getColorForKey }: ColorGenerator) => (
const [newTagName, setNewTagName] = useState(tag); const [newTagName, setNewTagName] = useState(tag);
const [color, setColor] = useState(getColorForKey(tag)); const [color, setColor] = useState(getColorForKey(tag));
const [showColorPicker, toggleColorPicker, , hideColorPicker] = useToggle(); const [showColorPicker, toggleColorPicker, , hideColorPicker] = useToggle();
const { editing, error, errorData } = tagEdit; const { editing, error, edited, errorData } = tagEdit;
const saveTag = handleEventPreventingDefault( const saveTag = handleEventPreventingDefault(
async () => editTag(tag, newTagName, color) async () => editTag({ oldName: tag, newName: newTagName, color })
.then(() => tagEdited(tag, newTagName, color))
.then(toggle) .then(toggle)
.catch(() => {}), .catch(() => {}),
); );
const onClosed = pipe(hideColorPicker, () => edited && tagEdited({ oldName: tag, newName: newTagName, color }));
return ( return (
<Modal isOpen={isOpen} toggle={toggle} centered onClosed={hideColorPicker}> <Modal isOpen={isOpen} toggle={toggle} centered onClosed={onClosed}>
<form name="editTag" onSubmit={saveTag}> <form name="editTag" onSubmit={saveTag}>
<ModalHeader toggle={toggle}>Edit tag</ModalHeader> <ModalHeader toggle={toggle}>Edit tag</ModalHeader>
<ModalBody> <ModalBody>

View file

@ -1,52 +1,48 @@
import { Action, Dispatch } from 'redux'; import { createAction, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { buildReducer } from '../../utils/helpers/redux'; import { createAsyncThunk } 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_TAG_START = 'shlink/deleteTag/DELETE_TAG_START'; const DELETE_TAG = 'shlink/deleteTag/DELETE_TAG';
export const DELETE_TAG_ERROR = 'shlink/deleteTag/DELETE_TAG_ERROR'; const TAG_DELETED = 'shlink/deleteTag/TAG_DELETED';
export const DELETE_TAG = 'shlink/deleteTag/DELETE_TAG';
export const TAG_DELETED = 'shlink/deleteTag/TAG_DELETED';
export interface TagDeletion { export interface TagDeletion {
deleting: boolean; deleting: boolean;
deleted: boolean;
error: boolean; error: boolean;
errorData?: ProblemDetailsError; errorData?: ProblemDetailsError;
} }
export interface DeleteTagAction extends Action<string> { export type DeleteTagAction = PayloadAction<string>;
tag: string;
}
const initialState: TagDeletion = { const initialState: TagDeletion = {
deleting: false, deleting: false,
deleted: false,
error: false, error: false,
}; };
export default buildReducer<TagDeletion, ApiErrorAction>({ export const tagDeleted = createAction<string>(TAG_DELETED);
[DELETE_TAG_START]: () => ({ deleting: true, error: false }),
[DELETE_TAG_ERROR]: (_, { errorData }) => ({ deleting: false, error: true, errorData }),
[DELETE_TAG]: () => ({ deleting: false, error: false }),
}, initialState);
export const deleteTag = (buildShlinkApiClient: ShlinkApiClientBuilder) => (tag: string) => async ( export const tagDeleteReducerCreator = (buildShlinkApiClient: ShlinkApiClientBuilder) => {
dispatch: Dispatch, const deleteTag = createAsyncThunk(DELETE_TAG, async (tag: string, { getState }): Promise<void> => {
getState: GetState, const { deleteTags } = buildShlinkApiClient(getState);
) => {
dispatch({ type: DELETE_TAG_START });
const { deleteTags } = buildShlinkApiClient(getState);
try {
await deleteTags([tag]); await deleteTags([tag]);
dispatch({ type: DELETE_TAG }); });
} catch (e: any) {
dispatch<ApiErrorAction>({ type: DELETE_TAG_ERROR, errorData: parseApiError(e) });
throw e; const { reducer } = createSlice({
} name: 'tagDeleteReducer',
initialState,
reducers: {},
extraReducers: (builder) => {
builder.addCase(deleteTag.pending, () => ({ deleting: true, deleted: false, error: false }));
builder.addCase(
deleteTag.rejected,
(_, { error }) => ({ deleting: false, deleted: false, error: true, errorData: parseApiError(error) }),
);
builder.addCase(deleteTag.fulfilled, () => ({ deleting: false, deleted: true, error: false }));
},
});
return { reducer, deleteTag };
}; };
export const tagDeleted = (tag: string): DeleteTagAction => ({ type: TAG_DELETED, tag });

View file

@ -1,72 +1,68 @@
import { pick } from 'ramda'; import { pick } from 'ramda';
import { Action, Dispatch } from 'redux'; import { createAction, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { buildReducer } from '../../utils/helpers/redux'; import { createAsyncThunk } 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;
newName: string; newName?: string;
editing: boolean; editing: boolean;
edited: boolean;
error: boolean; error: boolean;
errorData?: ProblemDetailsError; errorData?: ProblemDetailsError;
} }
export interface EditTagAction extends Action<string> { export interface EditTag {
oldName: string; oldName: string;
newName: string; newName: string;
color: string; color: string;
} }
export type EditTagAction = PayloadAction<EditTag>;
const initialState: TagEdition = { const initialState: TagEdition = {
oldName: '',
newName: '',
editing: false, editing: false,
edited: false,
error: false, error: false,
}; };
export default buildReducer<TagEdition, EditTagAction & ApiErrorAction>({ export const tagEdited = createAction<EditTag>(TAG_EDITED);
[EDIT_TAG_START]: (state) => ({ ...state, editing: true, error: false }),
[EDIT_TAG_ERROR]: (state, { errorData }) => ({ ...state, editing: false, error: true, errorData }),
[EDIT_TAG]: (_, action) => ({
...pick(['oldName', 'newName'], action),
editing: false,
error: false,
}),
}, initialState);
export const editTag = (buildShlinkApiClient: ShlinkApiClientBuilder, colorGenerator: ColorGenerator) => ( export const tagEditReducerCreator = (buildShlinkApiClient: ShlinkApiClientBuilder, colorGenerator: ColorGenerator) => {
oldName: string, const editTag = createAsyncThunk(
newName: string, EDIT_TAG,
color: string, async ({ oldName, newName, color }: EditTag, { getState }): Promise<EditTag> => {
) => async (dispatch: Dispatch, getState: GetState) => { await buildShlinkApiClient(getState).editTag(oldName, newName);
dispatch({ type: EDIT_TAG_START }); colorGenerator.setColorForKey(newName, color);
const { editTag: shlinkEditTag } = buildShlinkApiClient(getState);
try { return { oldName, newName, color };
await shlinkEditTag(oldName, newName); },
colorGenerator.setColorForKey(newName, color); );
dispatch({ type: EDIT_TAG, oldName, newName });
} catch (e: any) {
dispatch<ApiErrorAction>({ type: EDIT_TAG_ERROR, errorData: parseApiError(e) });
throw e; 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 };
}; };
export const tagEdited = (oldName: string, newName: string, color: string): EditTagAction => ({
type: TAG_EDITED,
oldName,
newName,
color,
});

View file

@ -1,6 +1,6 @@
import { isEmpty, reject } from 'ramda'; import { isEmpty, reject } from 'ramda';
import { Action, Dispatch } from 'redux'; import { Action, Dispatch } from 'redux';
import { CREATE_VISITS, CreateVisitsAction } from '../../visits/reducers/visitCreation'; import { createNewVisits, CreateVisitsAction } from '../../visits/reducers/visitCreation';
import { buildReducer } from '../../utils/helpers/redux'; import { buildReducer } from '../../utils/helpers/redux';
import { ShlinkTags } from '../../api/types'; import { ShlinkTags } from '../../api/types';
import { GetState } from '../../container/types'; import { GetState } from '../../container/types';
@ -10,8 +10,8 @@ import { parseApiError } from '../../api/utils';
import { TagStats } from '../data'; import { TagStats } from '../data';
import { ApiErrorAction } from '../../api/types/actions'; import { ApiErrorAction } from '../../api/types/actions';
import { CREATE_SHORT_URL, CreateShortUrlAction } from '../../short-urls/reducers/shortUrlCreation'; import { CREATE_SHORT_URL, CreateShortUrlAction } from '../../short-urls/reducers/shortUrlCreation';
import { DeleteTagAction, TAG_DELETED } from './tagDelete'; import { DeleteTagAction, tagDeleted } from './tagDelete';
import { EditTagAction, TAG_EDITED } from './tagEdit'; import { EditTagAction, tagEdited } from './tagEdit';
import { ProblemDetailsError } from '../../api/types/errors'; import { ProblemDetailsError } from '../../api/types/errors';
export const LIST_TAGS_START = 'shlink/tagsList/LIST_TAGS_START'; export const LIST_TAGS_START = 'shlink/tagsList/LIST_TAGS_START';
@ -85,21 +85,21 @@ export default buildReducer<TagsList, TagsCombinedAction>({
[LIST_TAGS_START]: () => ({ ...initialState, loading: true }), [LIST_TAGS_START]: () => ({ ...initialState, loading: true }),
[LIST_TAGS_ERROR]: (_, { errorData }) => ({ ...initialState, error: true, errorData }), [LIST_TAGS_ERROR]: (_, { errorData }) => ({ ...initialState, error: true, errorData }),
[LIST_TAGS]: (_, { tags, stats }) => ({ ...initialState, stats, tags, filteredTags: tags }), [LIST_TAGS]: (_, { tags, stats }) => ({ ...initialState, stats, tags, filteredTags: tags }),
[TAG_DELETED]: (state, { tag }) => ({ [tagDeleted.toString()]: (state, { payload: tag }) => ({
...state, ...state,
tags: rejectTag(state.tags, tag), tags: rejectTag(state.tags, tag),
filteredTags: rejectTag(state.filteredTags, tag), filteredTags: rejectTag(state.filteredTags, tag),
}), }),
[TAG_EDITED]: (state, { oldName, newName }) => ({ [tagEdited.toString()]: (state, { payload }) => ({
...state, ...state,
tags: state.tags.map(renameTag(oldName, newName)).sort(), tags: state.tags.map(renameTag(payload.oldName, payload.newName)).sort(),
filteredTags: state.filteredTags.map(renameTag(oldName, newName)).sort(), filteredTags: state.filteredTags.map(renameTag(payload.oldName, payload.newName)).sort(),
}), }),
[FILTER_TAGS]: (state, { searchTerm }) => ({ [FILTER_TAGS]: (state, { searchTerm }) => ({
...state, ...state,
filteredTags: state.tags.filter((tag) => tag.toLowerCase().match(searchTerm.toLowerCase())), filteredTags: state.tags.filter((tag) => tag.toLowerCase().match(searchTerm.toLowerCase())),
}), }),
[CREATE_VISITS]: (state, { payload }) => ({ [createNewVisits.toString()]: (state, { payload }) => ({
...state, ...state,
stats: increaseVisitsForTags(calculateVisitsPerTag(payload.createdVisits), state.stats), stats: increaseVisitsForTags(calculateVisitsPerTag(payload.createdVisits), state.stats),
}), }),

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';
@ -5,8 +6,8 @@ import { DeleteTagConfirmModal } from '../helpers/DeleteTagConfirmModal';
import { EditTagModal } from '../helpers/EditTagModal'; 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 { tagDeleted, tagDeleteReducerCreator } 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,13 @@ 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');
bottle.serviceFactory('tagDeleteReducerCreator', tagDeleteReducerCreator, 'buildShlinkApiClient');
bottle.serviceFactory('tagDeleteReducer', prop('reducer'), 'tagDeleteReducerCreator');
// Actions // Actions
const listTagsActionFactory = (force: boolean) => const listTagsActionFactory = (force: boolean) =>
({ buildShlinkApiClient }: IContainer) => listTags(buildShlinkApiClient, force); ({ buildShlinkApiClient }: IContainer) => listTags(buildShlinkApiClient, force);
@ -43,11 +51,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', prop('deleteTag'), 'tagDeleteReducerCreator');
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

@ -7,7 +7,7 @@ import { ShlinkVisitsParams } from '../../api/types';
import { ApiErrorAction } from '../../api/types/actions'; import { ApiErrorAction } from '../../api/types/actions';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common'; import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common';
import { CREATE_VISITS, CreateVisitsAction } from './visitCreation'; import { createNewVisits, CreateVisitsAction } from './visitCreation';
import { domainMatches } from '../../short-urls/helpers'; import { domainMatches } from '../../short-urls/helpers';
export const GET_DOMAIN_VISITS_START = 'shlink/domainVisits/GET_DOMAIN_VISITS_START'; export const GET_DOMAIN_VISITS_START = 'shlink/domainVisits/GET_DOMAIN_VISITS_START';
@ -56,7 +56,7 @@ export default buildReducer<DomainVisits, DomainVisitsCombinedAction>({
[GET_DOMAIN_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }), [GET_DOMAIN_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }),
[GET_DOMAIN_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }), [GET_DOMAIN_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }),
[GET_DOMAIN_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }), [GET_DOMAIN_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }),
[CREATE_VISITS]: (state, { payload }) => { [createNewVisits.toString()]: (state, { payload }) => {
const { domain, visits, query = {} } = state; const { domain, visits, query = {} } = state;
const { startDate, endDate } = query; const { startDate, endDate } = query;
const newVisits = payload.createdVisits const newVisits = payload.createdVisits

View file

@ -12,7 +12,7 @@ import { ShlinkVisitsParams } from '../../api/types';
import { ApiErrorAction } from '../../api/types/actions'; import { ApiErrorAction } from '../../api/types/actions';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common'; import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common';
import { CREATE_VISITS, CreateVisitsAction } from './visitCreation'; import { createNewVisits, CreateVisitsAction } from './visitCreation';
export const GET_NON_ORPHAN_VISITS_START = 'shlink/orphanVisits/GET_NON_ORPHAN_VISITS_START'; export const GET_NON_ORPHAN_VISITS_START = 'shlink/orphanVisits/GET_NON_ORPHAN_VISITS_START';
export const GET_NON_ORPHAN_VISITS_ERROR = 'shlink/orphanVisits/GET_NON_ORPHAN_VISITS_ERROR'; export const GET_NON_ORPHAN_VISITS_ERROR = 'shlink/orphanVisits/GET_NON_ORPHAN_VISITS_ERROR';
@ -52,7 +52,7 @@ export default buildReducer<VisitsInfo, NonOrphanVisitsCombinedAction>({
[GET_NON_ORPHAN_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }), [GET_NON_ORPHAN_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }),
[GET_NON_ORPHAN_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }), [GET_NON_ORPHAN_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }),
[GET_NON_ORPHAN_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }), [GET_NON_ORPHAN_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }),
[CREATE_VISITS]: (state, { payload }) => { [createNewVisits.toString()]: (state, { payload }) => {
const { visits, query = {} } = state; const { visits, query = {} } = state;
const { startDate, endDate } = query; const { startDate, endDate } = query;
const newVisits = payload.createdVisits const newVisits = payload.createdVisits

View file

@ -15,7 +15,7 @@ import { isOrphanVisit } from '../types/helpers';
import { ApiErrorAction } from '../../api/types/actions'; import { ApiErrorAction } from '../../api/types/actions';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common'; import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common';
import { CREATE_VISITS, CreateVisitsAction } from './visitCreation'; import { createNewVisits, CreateVisitsAction } from './visitCreation';
export const GET_ORPHAN_VISITS_START = 'shlink/orphanVisits/GET_ORPHAN_VISITS_START'; export const GET_ORPHAN_VISITS_START = 'shlink/orphanVisits/GET_ORPHAN_VISITS_START';
export const GET_ORPHAN_VISITS_ERROR = 'shlink/orphanVisits/GET_ORPHAN_VISITS_ERROR'; export const GET_ORPHAN_VISITS_ERROR = 'shlink/orphanVisits/GET_ORPHAN_VISITS_ERROR';
@ -55,7 +55,7 @@ export default buildReducer<VisitsInfo, OrphanVisitsCombinedAction>({
[GET_ORPHAN_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }), [GET_ORPHAN_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }),
[GET_ORPHAN_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }), [GET_ORPHAN_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }),
[GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }), [GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }),
[CREATE_VISITS]: (state, { payload }) => { [createNewVisits.toString()]: (state, { payload }) => {
const { visits, query = {} } = state; const { visits, query = {} } = state;
const { startDate, endDate } = query; const { startDate, endDate } = query;
const newVisits = payload.createdVisits const newVisits = payload.createdVisits

View file

@ -9,7 +9,7 @@ import { ShlinkVisitsParams } from '../../api/types';
import { ApiErrorAction } from '../../api/types/actions'; import { ApiErrorAction } from '../../api/types/actions';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common'; import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common';
import { CREATE_VISITS, CreateVisitsAction } from './visitCreation'; import { createNewVisits, CreateVisitsAction } from './visitCreation';
export const GET_SHORT_URL_VISITS_START = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_START'; export const GET_SHORT_URL_VISITS_START = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_START';
export const GET_SHORT_URL_VISITS_ERROR = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_ERROR'; export const GET_SHORT_URL_VISITS_ERROR = 'shlink/shortUrlVisits/GET_SHORT_URL_VISITS_ERROR';
@ -60,7 +60,7 @@ export default buildReducer<ShortUrlVisits, ShortUrlVisitsCombinedAction>({
[GET_SHORT_URL_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }), [GET_SHORT_URL_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }),
[GET_SHORT_URL_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }), [GET_SHORT_URL_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }),
[GET_SHORT_URL_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }), [GET_SHORT_URL_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }),
[CREATE_VISITS]: (state, { payload }) => { [createNewVisits.toString()]: (state, { payload }) => {
const { shortCode, domain, visits, query = {} } = state; const { shortCode, domain, visits, query = {} } = state;
const { startDate, endDate } = query; const { startDate, endDate } = query;
const newVisits = payload.createdVisits const newVisits = payload.createdVisits

View file

@ -7,7 +7,7 @@ import { ShlinkVisitsParams } from '../../api/types';
import { ApiErrorAction } from '../../api/types/actions'; import { ApiErrorAction } from '../../api/types/actions';
import { isBetween } from '../../utils/helpers/date'; import { isBetween } from '../../utils/helpers/date';
import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common'; import { getVisitsWithLoader, lastVisitLoaderForLoader } from './common';
import { CREATE_VISITS, CreateVisitsAction } from './visitCreation'; import { createNewVisits, CreateVisitsAction } from './visitCreation';
export const GET_TAG_VISITS_START = 'shlink/tagVisits/GET_TAG_VISITS_START'; export const GET_TAG_VISITS_START = 'shlink/tagVisits/GET_TAG_VISITS_START';
export const GET_TAG_VISITS_ERROR = 'shlink/tagVisits/GET_TAG_VISITS_ERROR'; export const GET_TAG_VISITS_ERROR = 'shlink/tagVisits/GET_TAG_VISITS_ERROR';
@ -53,7 +53,7 @@ export default buildReducer<TagVisits, TagsVisitsCombinedAction>({
[GET_TAG_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }), [GET_TAG_VISITS_CANCEL]: (state) => ({ ...state, cancelLoad: true }),
[GET_TAG_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }), [GET_TAG_VISITS_PROGRESS_CHANGED]: (state, { progress }) => ({ ...state, progress }),
[GET_TAG_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }), [GET_TAG_VISITS_FALLBACK_TO_INTERVAL]: (state, { fallbackInterval }) => ({ ...state, fallbackInterval }),
[CREATE_VISITS]: (state, { payload }) => { [createNewVisits.toString()]: (state, { payload }) => {
const { tag, visits, query = {} } = state; const { tag, visits, query = {} } = state;
const { startDate, endDate } = query; const { startDate, endDate } = query;
const newVisits = payload.createdVisits const newVisits = payload.createdVisits

View file

@ -1,7 +1,7 @@
import { createAction, PayloadAction } from '@reduxjs/toolkit'; import { createAction, PayloadAction } from '@reduxjs/toolkit';
import { CreateVisit } from '../types'; import { CreateVisit } from '../types';
export const CREATE_VISITS = 'shlink/visitCreation/CREATE_VISITS'; const CREATE_VISITS = 'shlink/visitCreation/CREATE_VISITS';
export type CreateVisitsAction = PayloadAction<{ export type CreateVisitsAction = PayloadAction<{
createdVisits: CreateVisit[]; createdVisits: CreateVisit[];

View file

@ -4,7 +4,7 @@ import { ShlinkApiClientBuilder } from '../../api/services/ShlinkApiClientBuilde
import { GetState } from '../../container/types'; import { GetState } from '../../container/types';
import { buildReducer } from '../../utils/helpers/redux'; import { buildReducer } from '../../utils/helpers/redux';
import { groupNewVisitsByType } from '../types/helpers'; import { groupNewVisitsByType } from '../types/helpers';
import { CREATE_VISITS, CreateVisitsAction } from './visitCreation'; import { createNewVisits, CreateVisitsAction } from './visitCreation';
export const GET_OVERVIEW_START = 'shlink/visitsOverview/GET_OVERVIEW_START'; export const GET_OVERVIEW_START = 'shlink/visitsOverview/GET_OVERVIEW_START';
export const GET_OVERVIEW_ERROR = 'shlink/visitsOverview/GET_OVERVIEW_ERROR'; export const GET_OVERVIEW_ERROR = 'shlink/visitsOverview/GET_OVERVIEW_ERROR';
@ -30,7 +30,7 @@ export default buildReducer<VisitsOverview, GetVisitsOverviewAction & CreateVisi
[GET_OVERVIEW_START]: () => ({ ...initialState, loading: true }), [GET_OVERVIEW_START]: () => ({ ...initialState, loading: true }),
[GET_OVERVIEW_ERROR]: () => ({ ...initialState, error: true }), [GET_OVERVIEW_ERROR]: () => ({ ...initialState, error: true }),
[GET_OVERVIEW]: (_, { visitsCount, orphanVisitsCount }) => ({ ...initialState, visitsCount, orphanVisitsCount }), [GET_OVERVIEW]: (_, { visitsCount, orphanVisitsCount }) => ({ ...initialState, visitsCount, orphanVisitsCount }),
[CREATE_VISITS]: ({ visitsCount, orphanVisitsCount = 0, ...rest }, { payload }) => { [createNewVisits.toString()]: ({ visitsCount, orphanVisitsCount = 0, ...rest }, { payload }) => {
const { regularVisits, orphanVisits } = groupNewVisitsByType(payload.createdVisits); const { regularVisits, orphanVisits } = groupNewVisitsByType(payload.createdVisits);
return { return {

View file

@ -6,12 +6,12 @@ import reducer, {
listShortUrls, listShortUrls,
} from '../../../src/short-urls/reducers/shortUrlsList'; } from '../../../src/short-urls/reducers/shortUrlsList';
import { SHORT_URL_DELETED } from '../../../src/short-urls/reducers/shortUrlDeletion'; import { SHORT_URL_DELETED } from '../../../src/short-urls/reducers/shortUrlDeletion';
import { CREATE_VISITS } from '../../../src/visits/reducers/visitCreation';
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 { ShlinkPaginator, ShlinkShortUrlsResponse } from '../../../src/api/types'; import { ShlinkPaginator, ShlinkShortUrlsResponse } from '../../../src/api/types';
import { CREATE_SHORT_URL } from '../../../src/short-urls/reducers/shortUrlCreation'; import { CREATE_SHORT_URL } from '../../../src/short-urls/reducers/shortUrlCreation';
import { SHORT_URL_EDITED } from '../../../src/short-urls/reducers/shortUrlEdition'; import { SHORT_URL_EDITED } from '../../../src/short-urls/reducers/shortUrlEdition';
import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
describe('shortUrlsListReducer', () => { describe('shortUrlsListReducer', () => {
const shortCode = 'abc123'; const shortCode = 'abc123';
@ -85,7 +85,7 @@ describe('shortUrlsListReducer', () => {
error: false, error: false,
}; };
expect(reducer(state, { type: CREATE_VISITS, payload: { createdVisits } } as any)).toEqual({ expect(reducer(state, { type: createNewVisits.toString(), payload: { createdVisits } } as any)).toEqual({
shortUrls: { shortUrls: {
data: [ data: [
{ shortCode, domain: 'example.com', visitsCount: 5 }, { shortCode, domain: 'example.com', visitsCount: 5 },

View file

@ -6,14 +6,14 @@ import { renderWithEvents } from '../../__helpers__/setUpTest';
describe('<DeleteTagConfirmModal />', () => { describe('<DeleteTagConfirmModal />', () => {
const tag = 'nodejs'; const tag = 'nodejs';
const deleteTag = jest.fn(); const deleteTag = jest.fn();
const tagDeleted = jest.fn(); const toggle = jest.fn();
const setUp = (tagDelete: TagDeletion) => renderWithEvents( const setUp = (tagDelete: TagDeletion) => renderWithEvents(
<DeleteTagConfirmModal <DeleteTagConfirmModal
tag={tag} tag={tag}
toggle={() => ''} toggle={toggle}
isOpen isOpen
deleteTag={deleteTag} deleteTag={deleteTag}
tagDeleted={tagDeleted} tagDeleted={jest.fn()}
tagDelete={tagDelete} tagDelete={tagDelete}
/>, />,
); );
@ -21,7 +21,7 @@ describe('<DeleteTagConfirmModal />', () => {
afterEach(jest.resetAllMocks); afterEach(jest.resetAllMocks);
it('asks confirmation for provided tag to be deleted', () => { it('asks confirmation for provided tag to be deleted', () => {
setUp({ error: false, deleting: false }); setUp({ error: false, deleted: false, deleting: false });
const delBtn = screen.getByRole('button', { name: 'Delete tag' }); const delBtn = screen.getByRole('button', { name: 'Delete tag' });
@ -33,12 +33,12 @@ describe('<DeleteTagConfirmModal />', () => {
}); });
it('shows error message when deletion failed', () => { it('shows error message when deletion failed', () => {
setUp({ error: true, deleting: false }); setUp({ error: true, deleted: false, deleting: false });
expect(screen.getByText('Something went wrong while deleting the tag :(')).toBeInTheDocument(); expect(screen.getByText('Something went wrong while deleting the tag :(')).toBeInTheDocument();
}); });
it('shows loading status while deleting', () => { it('shows loading status while deleting', () => {
setUp({ error: false, deleting: true }); setUp({ error: false, deleted: false, deleting: true });
const delBtn = screen.getByRole('button', { name: 'Deleting tag...' }); const delBtn = screen.getByRole('button', { name: 'Deleting tag...' });
@ -48,22 +48,21 @@ describe('<DeleteTagConfirmModal />', () => {
}); });
it('hides tag modal when btn is clicked', async () => { it('hides tag modal when btn is clicked', async () => {
const { user } = setUp({ error: false, deleting: false }); const { user } = setUp({ error: false, deleted: true, deleting: false });
await user.click(screen.getByRole('button', { name: 'Delete tag' })); await user.click(screen.getByRole('button', { name: 'Delete tag' }));
expect(deleteTag).toHaveBeenCalledTimes(1); expect(deleteTag).toHaveBeenCalledTimes(1);
expect(deleteTag).toHaveBeenCalledWith(tag); expect(deleteTag).toHaveBeenCalledWith(tag);
expect(tagDeleted).toHaveBeenCalledTimes(1); expect(toggle).toHaveBeenCalledTimes(1);
expect(tagDeleted).toHaveBeenCalledWith(tag);
}); });
it('does no further actions when modal is closed without deleting tag', async () => { it('does no further actions when modal is closed without deleting tag', async () => {
const { user } = setUp({ error: false, deleting: false }); const { user } = setUp({ error: false, deleted: true, deleting: false });
await user.click(screen.getByLabelText('Close')); await user.click(screen.getByLabelText('Close'));
expect(deleteTag).not.toHaveBeenCalled(); expect(deleteTag).not.toHaveBeenCalled();
expect(tagDeleted).not.toHaveBeenCalled(); expect(toggle).toHaveBeenCalled();
}); });
}); });

View file

@ -9,12 +9,11 @@ import { ProblemDetailsError } from '../../../src/api/types/errors';
describe('<EditTagModal />', () => { describe('<EditTagModal />', () => {
const EditTagModal = createEditTagModal(Mock.of<ColorGenerator>({ getColorForKey: jest.fn(() => 'green') })); const EditTagModal = createEditTagModal(Mock.of<ColorGenerator>({ getColorForKey: jest.fn(() => 'green') }));
const editTag = jest.fn().mockReturnValue(Promise.resolve()); const editTag = jest.fn().mockReturnValue(Promise.resolve());
const tagEdited = jest.fn().mockReturnValue(Promise.resolve());
const toggle = jest.fn(); const toggle = jest.fn();
const setUp = (tagEdit: Partial<TagEdition> = {}) => { const setUp = (tagEdit: Partial<TagEdition> = {}) => {
const edition = Mock.of<TagEdition>(tagEdit); const edition = Mock.of<TagEdition>(tagEdit);
return renderWithEvents( return renderWithEvents(
<EditTagModal isOpen tag="foo" tagEdit={edition} editTag={editTag} tagEdited={tagEdited} toggle={toggle} />, <EditTagModal isOpen tag="foo" tagEdit={edition} editTag={editTag} tagEdited={jest.fn()} toggle={toggle} />,
); );
}; };
@ -30,7 +29,6 @@ describe('<EditTagModal />', () => {
expect(toggle).toHaveBeenCalledTimes(2); expect(toggle).toHaveBeenCalledTimes(2);
expect(editTag).not.toHaveBeenCalled(); expect(editTag).not.toHaveBeenCalled();
expect(tagEdited).not.toHaveBeenCalled();
}); });
it.each([ it.each([
@ -63,12 +61,12 @@ describe('<EditTagModal />', () => {
const { user } = setUp(); const { user } = setUp();
expect(editTag).not.toHaveBeenCalled(); expect(editTag).not.toHaveBeenCalled();
expect(tagEdited).not.toHaveBeenCalled(); expect(toggle).not.toHaveBeenCalled();
await user.click(screen.getByRole('button', { name: 'Save' })); await user.click(screen.getByRole('button', { name: 'Save' }));
expect(editTag).toHaveBeenCalled(); expect(editTag).toHaveBeenCalled();
expect(tagEdited).toHaveBeenCalled(); expect(toggle).toHaveBeenCalled();
}); });
it('changes color when changing on color picker', async () => { it('changes color when changing on color picker', async () => {

View file

@ -1,34 +1,36 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import reducer, { import { tagDeleted, tagDeleteReducerCreator } from '../../../src/tags/reducers/tagDelete';
DELETE_TAG_START,
DELETE_TAG_ERROR,
DELETE_TAG,
TAG_DELETED,
tagDeleted,
deleteTag,
} from '../../../src/tags/reducers/tagDelete';
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';
describe('tagDeleteReducer', () => { describe('tagDeleteReducer', () => {
const deleteTagsCall = jest.fn();
const buildShlinkApiClient = () => Mock.of<ShlinkApiClient>({ deleteTags: deleteTagsCall });
const { reducer, deleteTag } = tagDeleteReducerCreator(buildShlinkApiClient);
beforeEach(jest.clearAllMocks);
describe('reducer', () => { describe('reducer', () => {
it('returns loading on DELETE_TAG_START', () => { it('returns loading on DELETE_TAG_START', () => {
expect(reducer(undefined, { type: DELETE_TAG_START })).toEqual({ expect(reducer(undefined, { type: deleteTag.pending.toString() })).toEqual({
deleting: true, deleting: true,
deleted: false,
error: false, error: false,
}); });
}); });
it('returns error on DELETE_TAG_ERROR', () => { it('returns error on DELETE_TAG_ERROR', () => {
expect(reducer(undefined, { type: DELETE_TAG_ERROR })).toEqual({ expect(reducer(undefined, { type: deleteTag.rejected.toString() })).toEqual({
deleting: false, deleting: false,
deleted: false,
error: true, error: true,
}); });
}); });
it('returns tag names on DELETE_TAG', () => { it('returns tag names on DELETE_TAG', () => {
expect(reducer(undefined, { type: DELETE_TAG })).toEqual({ expect(reducer(undefined, { type: deleteTag.fulfilled.toString() })).toEqual({
deleting: false, deleting: false,
deleted: true,
error: false, error: false,
}); });
}); });
@ -37,53 +39,46 @@ describe('tagDeleteReducer', () => {
describe('tagDeleted', () => { describe('tagDeleted', () => {
it('returns action based on provided params', () => it('returns action based on provided params', () =>
expect(tagDeleted('foo')).toEqual({ expect(tagDeleted('foo')).toEqual({
type: TAG_DELETED, type: tagDeleted.toString(),
tag: 'foo', payload: 'foo',
})); }));
}); });
describe('deleteTag', () => { describe('deleteTag', () => {
const createApiClientMock = (result: Promise<any>) => Mock.of<ShlinkApiClient>({
deleteTags: jest.fn(async () => result),
});
const dispatch = jest.fn(); const dispatch = jest.fn();
const getState = () => Mock.all<ShlinkState>(); const getState = () => Mock.all<ShlinkState>();
afterEach(() => dispatch.mockReset());
it('calls API on success', async () => { it('calls API on success', async () => {
const tag = 'foo'; const tag = 'foo';
const apiClientMock = createApiClientMock(Promise.resolve()); deleteTagsCall.mockResolvedValue(undefined);
const dispatchable = deleteTag(() => apiClientMock)(tag);
await dispatchable(dispatch, getState); await deleteTag(tag)(dispatch, getState, {});
expect(apiClientMock.deleteTags).toHaveBeenCalledTimes(1); expect(deleteTagsCall).toHaveBeenCalledTimes(1);
expect(apiClientMock.deleteTags).toHaveBeenNthCalledWith(1, [tag]); expect(deleteTagsCall).toHaveBeenNthCalledWith(1, [tag]);
expect(dispatch).toHaveBeenCalledTimes(2); expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: DELETE_TAG_START }); expect(dispatch).toHaveBeenNthCalledWith(1, expect.objectContaining({ type: deleteTag.pending.toString() }));
expect(dispatch).toHaveBeenNthCalledWith(2, { type: DELETE_TAG }); expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({ type: deleteTag.fulfilled.toString() }));
}); });
it('throws on error', async () => { it('throws on error', async () => {
const error = 'Error'; const error = 'Error';
const tag = 'foo'; const tag = 'foo';
const apiClientMock = createApiClientMock(Promise.reject(error)); deleteTagsCall.mockRejectedValue(error);
const dispatchable = deleteTag(() => apiClientMock)(tag);
try { try {
await dispatchable(dispatch, getState); await deleteTag(tag)(dispatch, getState, {});
} catch (e) { } catch (e) {
expect(e).toEqual(error); expect(e).toEqual(error);
} }
expect(apiClientMock.deleteTags).toHaveBeenCalledTimes(1); expect(deleteTagsCall).toHaveBeenCalledTimes(1);
expect(apiClientMock.deleteTags).toHaveBeenNthCalledWith(1, [tag]); expect(deleteTagsCall).toHaveBeenNthCalledWith(1, [tag]);
expect(dispatch).toHaveBeenCalledTimes(2); expect(dispatch).toHaveBeenCalledTimes(2);
expect(dispatch).toHaveBeenNthCalledWith(1, { type: DELETE_TAG_START }); expect(dispatch).toHaveBeenNthCalledWith(1, expect.objectContaining({ type: deleteTag.pending.toString() }));
expect(dispatch).toHaveBeenNthCalledWith(2, { type: DELETE_TAG_ERROR }); expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({ type: deleteTag.rejected.toString() }));
}); });
}); });
}); });

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,29 +8,35 @@ 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,
error: false, error: false,
oldName: '',
newName: '',
}); });
}); });
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,
error: true, error: true,
oldName: '',
newName: '',
}); });
}); });
it('returns tag names on EDIT_TAG', () => { it('returns tag names on EDIT_TAG', () => {
expect(reducer(undefined, { type: EDIT_TAG, oldName, newName, color })).toEqual({ expect(reducer(undefined, {
type: editTag.fulfilled.toString(),
payload: { oldName, newName, color },
})).toEqual({
editing: false, editing: false,
edited: true,
error: false, error: false,
oldName: 'foo', oldName: 'foo',
newName: 'bar', newName: 'bar',
@ -48,62 +46,59 @@ describe('tagEditReducer', () => {
describe('tagEdited', () => { describe('tagEdited', () => {
it('returns action based on provided params', () => it('returns action based on provided params', () =>
expect(tagEdited('foo', 'bar', '#ff0000')).toEqual({ expect(tagEdited({ oldName: 'foo', newName: 'bar', color: '#ff0000' })).toEqual({
type: TAG_EDITED, type: tagEdited.toString(),
oldName: 'foo', payload: {
newName: 'bar', oldName: 'foo',
color: '#ff0000', newName: 'bar',
color: '#ff0000',
},
})); }));
}); });
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, { type: EDIT_TAG, oldName, newName }); expect(dispatch).toHaveBeenNthCalledWith(2, expect.objectContaining({
type: editTag.fulfilled.toString(),
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

@ -8,11 +8,11 @@ import reducer, {
listTags, listTags,
TagsList, TagsList,
} from '../../../src/tags/reducers/tagsList'; } from '../../../src/tags/reducers/tagsList';
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';
import { tagDeleted } from '../../../src/tags/reducers/tagDelete';
describe('tagsListReducer', () => { describe('tagsListReducer', () => {
const state = (props: Partial<TagsList>) => Mock.of<TagsList>(props); const state = (props: Partial<TagsList>) => Mock.of<TagsList>(props);
@ -48,7 +48,10 @@ describe('tagsListReducer', () => {
const tag = 'foo'; const tag = 'foo';
const expectedTags = ['bar', 'baz']; const expectedTags = ['bar', 'baz'];
expect(reducer(state({ tags, filteredTags: tags }), { type: TAG_DELETED, tag } as any)).toEqual({ expect(reducer(
state({ tags, filteredTags: tags }),
{ type: tagDeleted.toString(), payload: tag } as any,
)).toEqual({
tags: expectedTags, tags: expectedTags,
filteredTags: expectedTags, filteredTags: expectedTags,
}); });
@ -60,7 +63,13 @@ describe('tagsListReducer', () => {
const newName = 'renamed'; const newName = 'renamed';
const expectedTags = ['foo', 'renamed', 'baz'].sort(); const expectedTags = ['foo', 'renamed', 'baz'].sort();
expect(reducer(state({ tags, filteredTags: tags }), { type: TAG_EDITED, oldName, newName } as any)).toEqual({ expect(reducer(
state({ tags, filteredTags: tags }),
{
type: tagEdited.toString(),
payload: { oldName, newName },
} as any,
)).toEqual({
tags: expectedTags, tags: expectedTags,
filteredTags: expectedTags, filteredTags: expectedTags,
}); });

View file

@ -13,7 +13,6 @@ import reducer, {
DomainVisits, DomainVisits,
DEFAULT_DOMAIN, DEFAULT_DOMAIN,
} from '../../../src/visits/reducers/domainVisits'; } from '../../../src/visits/reducers/domainVisits';
import { CREATE_VISITS } from '../../../src/visits/reducers/visitCreation';
import { rangeOf } from '../../../src/utils/utils'; import { rangeOf } from '../../../src/utils/utils';
import { Visit } from '../../../src/visits/types'; import { Visit } from '../../../src/visits/types';
import { ShlinkVisits } from '../../../src/api/types'; import { ShlinkVisits } from '../../../src/api/types';
@ -22,6 +21,7 @@ import { ShlinkState } from '../../../src/container/types';
import { formatIsoDate } from '../../../src/utils/helpers/date'; import { formatIsoDate } from '../../../src/utils/helpers/date';
import { DateInterval } from '../../../src/utils/dates/types'; import { DateInterval } from '../../../src/utils/dates/types';
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
describe('domainVisitsReducer', () => { describe('domainVisitsReducer', () => {
const now = new Date(); const now = new Date();
@ -134,7 +134,7 @@ describe('domainVisitsReducer', () => {
}); });
const { visits } = reducer(prevState, { const { visits } = reducer(prevState, {
type: CREATE_VISITS, type: createNewVisits.toString(),
payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] }, payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] },
} as any); } as any);

View file

@ -11,7 +11,6 @@ import reducer, {
GET_NON_ORPHAN_VISITS_PROGRESS_CHANGED, GET_NON_ORPHAN_VISITS_PROGRESS_CHANGED,
GET_NON_ORPHAN_VISITS_FALLBACK_TO_INTERVAL, GET_NON_ORPHAN_VISITS_FALLBACK_TO_INTERVAL,
} from '../../../src/visits/reducers/nonOrphanVisits'; } from '../../../src/visits/reducers/nonOrphanVisits';
import { CREATE_VISITS } from '../../../src/visits/reducers/visitCreation';
import { rangeOf } from '../../../src/utils/utils'; import { rangeOf } from '../../../src/utils/utils';
import { Visit, VisitsInfo } from '../../../src/visits/types'; import { Visit, VisitsInfo } from '../../../src/visits/types';
import { ShlinkVisits } from '../../../src/api/types'; import { ShlinkVisits } from '../../../src/api/types';
@ -19,6 +18,7 @@ import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
import { formatIsoDate } from '../../../src/utils/helpers/date'; import { formatIsoDate } from '../../../src/utils/helpers/date';
import { DateInterval } from '../../../src/utils/dates/types'; import { DateInterval } from '../../../src/utils/dates/types';
import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
describe('nonOrphanVisitsReducer', () => { describe('nonOrphanVisitsReducer', () => {
const now = new Date(); const now = new Date();
@ -106,7 +106,7 @@ describe('nonOrphanVisitsReducer', () => {
const visit = Mock.of<Visit>({ date: formatIsoDate(now) ?? undefined }); const visit = Mock.of<Visit>({ date: formatIsoDate(now) ?? undefined });
const { visits } = reducer(prevState, { const { visits } = reducer(prevState, {
type: CREATE_VISITS, type: createNewVisits.toString(),
payload: { createdVisits: [{ visit }, { visit }] }, payload: { createdVisits: [{ visit }, { visit }] },
} as any); } as any);

View file

@ -11,7 +11,6 @@ import reducer, {
GET_ORPHAN_VISITS_PROGRESS_CHANGED, GET_ORPHAN_VISITS_PROGRESS_CHANGED,
GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL, GET_ORPHAN_VISITS_FALLBACK_TO_INTERVAL,
} from '../../../src/visits/reducers/orphanVisits'; } from '../../../src/visits/reducers/orphanVisits';
import { CREATE_VISITS } from '../../../src/visits/reducers/visitCreation';
import { rangeOf } from '../../../src/utils/utils'; import { rangeOf } from '../../../src/utils/utils';
import { Visit, VisitsInfo } from '../../../src/visits/types'; import { Visit, VisitsInfo } from '../../../src/visits/types';
import { ShlinkVisits } from '../../../src/api/types'; import { ShlinkVisits } from '../../../src/api/types';
@ -19,6 +18,7 @@ import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
import { formatIsoDate } from '../../../src/utils/helpers/date'; import { formatIsoDate } from '../../../src/utils/helpers/date';
import { DateInterval } from '../../../src/utils/dates/types'; import { DateInterval } from '../../../src/utils/dates/types';
import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
describe('orphanVisitsReducer', () => { describe('orphanVisitsReducer', () => {
const now = new Date(); const now = new Date();
@ -106,7 +106,7 @@ describe('orphanVisitsReducer', () => {
const visit = Mock.of<Visit>({ date: formatIsoDate(now) ?? undefined }); const visit = Mock.of<Visit>({ date: formatIsoDate(now) ?? undefined });
const { visits } = reducer(prevState, { const { visits } = reducer(prevState, {
type: CREATE_VISITS, type: createNewVisits.toString(),
payload: { createdVisits: [{ visit }, { visit }] }, payload: { createdVisits: [{ visit }, { visit }] },
} as any); } as any);

View file

@ -12,7 +12,6 @@ import reducer, {
GET_SHORT_URL_VISITS_FALLBACK_TO_INTERVAL, GET_SHORT_URL_VISITS_FALLBACK_TO_INTERVAL,
ShortUrlVisits, ShortUrlVisits,
} from '../../../src/visits/reducers/shortUrlVisits'; } from '../../../src/visits/reducers/shortUrlVisits';
import { CREATE_VISITS } from '../../../src/visits/reducers/visitCreation';
import { rangeOf } from '../../../src/utils/utils'; import { rangeOf } from '../../../src/utils/utils';
import { Visit } from '../../../src/visits/types'; import { Visit } from '../../../src/visits/types';
import { ShlinkVisits } from '../../../src/api/types'; import { ShlinkVisits } from '../../../src/api/types';
@ -20,6 +19,7 @@ import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
import { formatIsoDate } from '../../../src/utils/helpers/date'; import { formatIsoDate } from '../../../src/utils/helpers/date';
import { DateInterval } from '../../../src/utils/dates/types'; import { DateInterval } from '../../../src/utils/dates/types';
import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
describe('shortUrlVisitsReducer', () => { describe('shortUrlVisitsReducer', () => {
const now = new Date(); const now = new Date();
@ -127,7 +127,7 @@ describe('shortUrlVisitsReducer', () => {
}); });
const { visits } = reducer(prevState, { const { visits } = reducer(prevState, {
type: CREATE_VISITS, type: createNewVisits.toString(),
payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] }, payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] },
} as any); } as any);

View file

@ -12,7 +12,6 @@ import reducer, {
GET_TAG_VISITS_FALLBACK_TO_INTERVAL, GET_TAG_VISITS_FALLBACK_TO_INTERVAL,
TagVisits, TagVisits,
} from '../../../src/visits/reducers/tagVisits'; } from '../../../src/visits/reducers/tagVisits';
import { CREATE_VISITS } from '../../../src/visits/reducers/visitCreation';
import { rangeOf } from '../../../src/utils/utils'; import { rangeOf } from '../../../src/utils/utils';
import { Visit } from '../../../src/visits/types'; import { Visit } from '../../../src/visits/types';
import { ShlinkVisits } from '../../../src/api/types'; import { ShlinkVisits } from '../../../src/api/types';
@ -20,6 +19,7 @@ import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
import { formatIsoDate } from '../../../src/utils/helpers/date'; import { formatIsoDate } from '../../../src/utils/helpers/date';
import { DateInterval } from '../../../src/utils/dates/types'; import { DateInterval } from '../../../src/utils/dates/types';
import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
describe('tagVisitsReducer', () => { describe('tagVisitsReducer', () => {
const now = new Date(); const now = new Date();
@ -127,7 +127,7 @@ describe('tagVisitsReducer', () => {
}); });
const { visits } = reducer(prevState, { const { visits } = reducer(prevState, {
type: CREATE_VISITS, type: createNewVisits.toString(),
payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] }, payload: { createdVisits: [{ shortUrl, visit: { date: formatIsoDate(now) ?? undefined } }] },
} as any); } as any);

View file

@ -1,5 +1,5 @@
import { Mock } from 'ts-mockery'; import { Mock } from 'ts-mockery';
import { CREATE_VISITS, createNewVisits } from '../../../src/visits/reducers/visitCreation'; import { createNewVisits } from '../../../src/visits/reducers/visitCreation';
import { ShortUrl } from '../../../src/short-urls/data'; import { ShortUrl } from '../../../src/short-urls/data';
import { Visit } from '../../../src/visits/types'; import { Visit } from '../../../src/visits/types';
@ -10,7 +10,7 @@ describe('visitCreationReducer', () => {
it('just returns the action with proper type', () => { it('just returns the action with proper type', () => {
expect(createNewVisits([{ shortUrl, visit }])).toEqual({ expect(createNewVisits([{ shortUrl, visit }])).toEqual({
type: CREATE_VISITS, type: createNewVisits.toString(),
payload: { createdVisits: [{ shortUrl, visit }] }, payload: { createdVisits: [{ shortUrl, visit }] },
}); });
}); });

View file

@ -7,7 +7,7 @@ import reducer, {
VisitsOverview, VisitsOverview,
loadVisitsOverview, loadVisitsOverview,
} from '../../../src/visits/reducers/visitsOverview'; } from '../../../src/visits/reducers/visitsOverview';
import { CREATE_VISITS, CreateVisitsAction } from '../../../src/visits/reducers/visitCreation'; import { createNewVisits, CreateVisitsAction } from '../../../src/visits/reducers/visitCreation';
import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient'; import { ShlinkApiClient } from '../../../src/api/services/ShlinkApiClient';
import { ShlinkVisitsOverview } from '../../../src/api/types'; import { ShlinkVisitsOverview } from '../../../src/api/types';
import { ShlinkState } from '../../../src/container/types'; import { ShlinkState } from '../../../src/container/types';
@ -51,7 +51,7 @@ describe('visitsOverviewReducer', () => {
const { visitsCount, orphanVisitsCount } = reducer( const { visitsCount, orphanVisitsCount } = reducer(
state({ visitsCount: 100, orphanVisitsCount: providedOrphanVisitsCount }), state({ visitsCount: 100, orphanVisitsCount: providedOrphanVisitsCount }),
{ {
type: CREATE_VISITS, type: createNewVisits.toString(),
payload: { payload: {
createdVisits: [ createdVisits: [
Mock.of<CreateVisit>({ visit: Mock.all<Visit>() }), Mock.of<CreateVisit>({ visit: Mock.all<Visit>() }),