Skip to content

Commit

Permalink
Merge pull request #288 from kortirso/issue_287
Browse files Browse the repository at this point in the history
IS-287 added caching for frontend
  • Loading branch information
kortirso committed Apr 3, 2024
2 parents 4377615 + 8b92057 commit d712adb
Show file tree
Hide file tree
Showing 11 changed files with 97 additions and 22 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
## Unreleased
### Added
- create users with only username
- caching for frontend

## [1.2.4] - 2024-03-28
### Added
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def teams_players
players(players_season_id_ids),
params: {
injuries: injuries(players_season_id_ids),
last_points: last_points
last_points: last_points,
week_id: week_id
}
).serializable_hash
end
Expand All @@ -50,6 +51,10 @@ def last_points
.where(weeks: { status: Week::ACTIVE })
.hashable_pluck('teams_players.players_season_id', :points)
end

def week_id
Week.where(season_id: @fantasy_team.season_id).coming.first.id
end
end
end
end
Expand Down
8 changes: 6 additions & 2 deletions app/javascript/components/BestPlayers/BestPlayers.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';

import { currentLocale, localizeValue } from '../../helpers';
import { currentLocale, localizeValue, fetchFromCache } from '../../helpers';
import { strings } from '../../locales';
import { sportsData } from '../../data';

Expand All @@ -23,7 +23,11 @@ export const BestPlayers = ({ weekUuid, seasonUuid, sportKind }) => {
const sportPositions = sportsData.positions[sportKind];

useEffect(() => {
const fetchTeams = async () => await teamsRequest(seasonUuid);
const fetchTeams = async () =>
await fetchFromCache(`season_teams_${seasonUuid}`, () =>
teamsRequest(seasonUuid),
);

const fetchBestSeasonPlayers = async () => await bestSeasonPlayersRequest(seasonUuid);
const fetchBestWeekPlayers = async () => await bestWeekPlayersRequest(seasonUuid, weekUuid);

Expand Down
14 changes: 11 additions & 3 deletions app/javascript/components/Squad/Squad.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useState, useEffect } from 'react';

import { sportsData } from '../../data';
import { currentLocale, localizeValue, csrfToken, convertDateTime } from '../../helpers';
import { currentLocale, localizeValue, csrfToken, convertDateTime, fetchFromCache } from '../../helpers';
import { strings } from '../../locales';

import { Flash } from '../../components/atoms';
Expand Down Expand Up @@ -47,10 +47,18 @@ export const Squad = ({
})

useEffect(() => {
const fetchTeams = async () =>
await fetchFromCache(`season_teams_${seasonUuid}`, () =>
teamsRequest(seasonUuid),
);

const fetchWeekOpponents = async () =>
await fetchFromCache(`week_opponents_${weekUuid}`, () =>
weekOpponentsRequest(weekUuid),
);

const fetchLineup = async () => await lineupRequest(lineupUuid);
const fetchTeams = async () => await teamsRequest(seasonUuid);
const fetchLineupPlayers = async () => await lineupPlayersRequest(lineupUuid);
const fetchWeekOpponents = async () => await weekOpponentsRequest(weekUuid);

Promise.all([fetchLineup(), fetchTeams(), fetchLineupPlayers(), fetchWeekOpponents()]).then(
([lineupData, teamsData, lineupPlayersData, weekOpponentsData]) =>
Expand Down
11 changes: 7 additions & 4 deletions app/javascript/components/SquadPoints/SquadPoints.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React, { useState, useEffect } from 'react';

import { sportsData } from '../../data';
import { currentLocale, localizeValue } from '../../helpers';
import { sportsData, statisticsOrder } from '../../data';
import { currentLocale, localizeValue, fetchFromCache } from '../../helpers';
import { strings } from '../../locales';
import { statisticsOrder } from '../../data';

import { Week, PlayerModal, PlayerCard } from '../../components';
import { teamsRequest } from '../../requests/teamsRequest';
Expand Down Expand Up @@ -34,7 +33,11 @@ export const SquadPoints = ({
const [playerUuid, setPlayerUuid] = useState();

useEffect(() => {
const fetchTeams = async () => await teamsRequest(seasonUuid);
const fetchTeams = async () =>
await fetchFromCache(`season_teams_${seasonUuid}`, () =>
teamsRequest(seasonUuid),
);

const fetchLineupPlayers = async () => await lineupPlayersRequest(lineupUuid);

Promise.all([fetchTeams(), fetchLineupPlayers()]).then(
Expand Down
13 changes: 10 additions & 3 deletions app/javascript/components/Transfers/Transfers.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useState, useMemo, useEffect } from 'react';

import { sportsData } from '../../data';
import { currentLocale, localizeValue, csrfToken, convertDateTime, currentWatches } from '../../helpers';
import { currentLocale, localizeValue, csrfToken, convertDateTime, currentWatches, fetchFromCache } from '../../helpers';
import { strings } from '../../locales';

import { Dropdown, Modal, Flash, Checkbox } from '../../components/atoms';
Expand Down Expand Up @@ -116,8 +116,15 @@ export const Transfers = ({
const sport = sportsData.sports[sportKind];

useEffect(() => {
const fetchTeams = async () => await teamsRequest(seasonUuid);
const fetchSeasonPlayers = async () => await seasonPlayersRequest(seasonUuid);
const fetchTeams = async () =>
await fetchFromCache(`season_teams_${seasonUuid}`, () =>
teamsRequest(seasonUuid),
);

const fetchSeasonPlayers = async () =>
await fetchFromCache(`season_players_${seasonUuid}`, () =>
seasonPlayersRequest(seasonUuid),
);

const fetchFantasyTeamPlayers = async () => {
if (!fantasyTeamCompleted) return [];
Expand Down
8 changes: 6 additions & 2 deletions app/javascript/components/TransfersStatus/TransfersStatus.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';

import { currentLocale, localizeValue } from '../../helpers';
import { currentLocale, localizeValue, fetchFromCache } from '../../helpers';
import { strings } from '../../locales';
import { sportsData } from '../../data';

Expand All @@ -22,7 +22,11 @@ export const TransfersStatus = ({ weekUuid, seasonUuid, sportKind }) => {
const sportPositions = sportsData.positions[sportKind];

useEffect(() => {
const fetchTeams = async () => await teamsRequest(seasonUuid);
const fetchTeams = async () =>
await fetchFromCache(`season_teams_${seasonUuid}`, () =>
teamsRequest(seasonUuid),
);

const fetchWeekTransfers = async () => await weekTransfersRequest(weekUuid);

Promise.all([fetchTeams(), fetchWeekTransfers()]).then(([teamsData, weekTransfersData]) =>
Expand Down
13 changes: 10 additions & 3 deletions app/javascript/components/Week/Week.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react';

import { currentLocale, convertDateTime, convertDate } from '../../helpers';
import { currentLocale, convertDateTime, convertDate, fetchFromCache } from '../../helpers';
import { strings } from '../../locales';
import { Arrow } from '../../assets';

Expand All @@ -20,8 +20,15 @@ export const Week = ({ id, teamNames }) => {
const [weekId, setWeekId] = useState(id);

useEffect(() => {
const fetchWeek = async () => await weekRequest(weekId);
const fetchGames = async () => await gamesRequest(weekId);
const fetchWeek = async () =>
await fetchFromCache(`week_${weekId}`, () =>
weekRequest(weekId)
);

const fetchGames = async () =>
await fetchFromCache(`week_games_${weekId}`, () =>
gamesRequest(weekId)
);

Promise.all([fetchWeek(), fetchGames()]).then(([weekData, gamesData]) => {
const groupedGames = gamesData.reduce((result, game) => {
Expand Down
36 changes: 36 additions & 0 deletions app/javascript/helpers/cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const MILLISECONDS_IN_DAY = 86400000;

const refreshCache = async (cacheKey, expirationTime, fetchFunction) => {
const result = await fetchFunction();

const jsonValue = JSON.stringify({
data: result,
expires_at: Date.now() + expirationTime,
});
await localStorage.setItem(cacheKey, jsonValue);

return result;
};

export const fetchFromCache = async (
cacheKey,
fetchFunction,
expirationTime = MILLISECONDS_IN_DAY,
useCache = true
) => {
// if no using cache
if (!useCache) {
return refreshCache(cacheKey, expirationTime, fetchFunction);
}

const jsonValue = await localStorage.getItem(cacheKey);
const parsedJsonValue = jsonValue != null ? JSON.parse(jsonValue) : null;

// if not expired -> return data from cache
if (parsedJsonValue && parsedJsonValue.expires_at > Date.now()) {
return parsedJsonValue.data;
}

// if cache is expired or no value in cache
return refreshCache(cacheKey, expirationTime, fetchFunction);
};
1 change: 1 addition & 0 deletions app/javascript/helpers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './localize';
export * from './csrf';
export * from './time';
export * from './watches';
export * from './cache';
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,19 @@ module Controllers
module FantasyTeams
module Players
class IndexSerializer < ::Players::SeasonSerializer
attribute :fixtures do |object|
week_id = Week.where(season_id: object.season_id).coming.first.id
attribute :fixtures do |object, params|
seasons_team = object.active_teams_player.seasons_team

# difficulties of next 4 games
Rails.cache.fetch(
['fantasy_teams_players_team_fixtures_v1', seasons_team.id, week_id],
['fantasy_teams_players_team_fixtures_v1', seasons_team.id, params[:week_id]],
expires_in: 12.hours,
race_condition_ttl: 10.seconds
) do
seasons_team
.games
.includes(:week, :home_season_team)
.where('weeks.id >= ?', week_id)
.where('weeks.id >= ?', params[:week_id])
.order('weeks.position ASC', 'start_at ASC')
.limit(4)
.hashable_pluck(:difficulty, :home_season_team_id)
Expand Down

0 comments on commit d712adb

Please sign in to comment.