Simplified reducer logic to update short URLs when new visits come

This commit is contained in:
Alejandro Celaya 2022-12-22 18:30:02 +01:00
parent b9285fd600
commit 2859ba6cd2

View file

@ -1,5 +1,5 @@
import { createSlice } from '@reduxjs/toolkit'; import { createSlice } from '@reduxjs/toolkit';
import { assoc, assocPath, last, pipe, reject } from 'ramda'; import { assocPath, last, pipe, reject } from 'ramda';
import { shortUrlMatches } from '../helpers'; import { shortUrlMatches } from '../helpers';
import { createNewVisits } from '../../visits/reducers/visitCreation'; import { createNewVisits } from '../../visits/reducers/visitCreation';
import { createAsyncThunk } from '../../utils/helpers/redux'; import { createAsyncThunk } from '../../utils/helpers/redux';
@ -101,18 +101,12 @@ export const shortUrlsListReducerCreator = (
(state, { payload }) => assocPath( (state, { payload }) => assocPath(
['shortUrls', 'data'], ['shortUrls', 'data'],
state.shortUrls?.data?.map( state.shortUrls?.data?.map(
(currentShortUrl) => { // Find the last of the new visit for this short URL, and pick its short URL. It will have an up-to-date amount of visits.
// Find the last of the new visit for this short URL, and pick the amount of visits from it (currentShortUrl) => last(
const lastVisit = last( payload.createdVisits.filter(
payload.createdVisits.filter( ({ shortUrl }) => shortUrl && shortUrlMatches(currentShortUrl, shortUrl.shortCode, shortUrl.domain),
({ shortUrl }) => shortUrl && shortUrlMatches(currentShortUrl, shortUrl.shortCode, shortUrl.domain), ),
), )?.shortUrl ?? currentShortUrl,
);
return lastVisit?.shortUrl
? assoc('visitsCount', lastVisit.shortUrl.visitsCount, currentShortUrl)
: currentShortUrl;
},
), ),
state, state,
), ),