Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions Backend/resolvers/GameResolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
FetchTop10GamesPerGenre,
FetchTop3Games
} from '../logic/MainPageLogicBackend.ts'
import { REVIEW_SCORE_JOIN } from '../logic/ReviewsLogicBackend.ts'
import type { Game } from '../Steam.ts'

const NAME_GROUP = `CASE
Expand All @@ -15,11 +16,12 @@ const NAME_GROUP = `CASE
END`

const SORT_SQL: Record<string, string> = {
'title-asc': `${NAME_GROUP} ASC, LOWER(g.game_name) ASC`,
'title-desc': `${NAME_GROUP} DESC, LOWER(g.game_name) DESC`,
'rating-desc': 'rs.review_score DESC NULLS LAST, rs.review_count DESC NULLS LAST',
'discount-desc': 'g.discount_percent DESC NULLS LAST',
'price-asc': 'g.current_price ASC NULLS LAST',
'price-desc': 'g.current_price DESC NULLS LAST',
'title-asc': `${NAME_GROUP} ASC, LOWER(g.game_name) ASC`,
'title-desc': `${NAME_GROUP} DESC, LOWER(g.game_name) DESC`
'price-desc': 'g.current_price DESC NULLS LAST'
}

function BuildGameFilter(search?: string | null, genres?: string[] | null, withRank = false) {
Expand Down Expand Up @@ -91,10 +93,12 @@ export const gameQueryResolvers = {
const { where, params, rank } = BuildGameFilter(search, genres, true)

const orderBy = [SORT_SQL[sort ?? ''], rank, 'g.game_id'].filter(Boolean).join(', ')
const join = sort === 'rating-desc' ? REVIEW_SCORE_JOIN : ''

const { rows } = await pool.query(
`SELECT ${GAME_COLUMNS}
FROM games g
${join}
${where}
ORDER BY ${orderBy}
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
Expand Down
6 changes: 6 additions & 0 deletions E2E/api/games.api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ test.describe('games', () => {
expect(names).toEqual([...names].sort((a, b) => a.localeCompare(b, 'en')))
})

test('sort rating-desc returns games without errors', async ({ request }) => {
const { data, errors } = await Gql<{ games: Game[] }>(request, GAMES, { l: 10, sort: 'rating-desc' })
expect(errors).toBeUndefined()
expect(data!.games).toHaveLength(10)
})

test('an unknown sort value is ignored, not an error', async ({ request }) => {
const { data, errors } = await Gql<{ games: Game[] }>(request, GAMES, { l: 3, sort: 'nonsense' })
expect(errors).toBeUndefined()
Expand Down
8 changes: 4 additions & 4 deletions Frontend/src/FrontendLogic/FriendLogicFrontend.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Gql } from './LogicConnection'
import type { Game } from '../types/Game'
import type { GameSummary } from '../types/Game'

export interface Friend {
id: number
Expand All @@ -10,7 +10,7 @@ export interface Friend {
}

const FRIEND_FIELDS = 'id username description setup favouriteGame { name img }'
const GAME_FIELDS = 'appid name price initialprice discount img genre description'
const GAME_FIELDS = 'appid name price initialprice discount img genre'

export async function GetFriends(userId: number): Promise<Friend[]> {
const data = await Gql<{ friends: Friend[] }>(
Expand All @@ -33,8 +33,8 @@ export async function AddFriend(userId: number, friendCode: string): Promise<Fri
return data.addFriend
}

export async function GetFriendWishlist(userId: number, friendId: number): Promise<Game[]> {
const data = await Gql<{ friendWishlist: Game[] }>(
export async function GetFriendWishlist(userId: number, friendId: number): Promise<GameSummary[]> {
const data = await Gql<{ friendWishlist: GameSummary[] }>(
`query($userId: Int!, $friendId: Int!) {
friendWishlist(userId: $userId, friendId: $friendId) { ${GAME_FIELDS} }
}`,
Expand Down
49 changes: 16 additions & 33 deletions Frontend/src/FrontendLogic/GameLogicFrontend.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Game } from '../types/Game'
import type { Game, GameSummary } from '../types/Game'
import { BACKEND_URL, NETWORK_ERROR_MESSAGE } from './LogicConnection'
import { OrNull, ReadStored, RemoveStored, WriteStored } from './Storage'

Expand All @@ -20,10 +20,10 @@ const GAMES_CACHE_PREFIX = `games:v2:${encodeURIComponent(BACKEND_URL)}:`

interface CachedGames {
fetchedAt: number
games: Game[]
games: GameSummary[]
}

function IsGame(value: unknown): value is Game {
function IsGameSummary(value: unknown): value is GameSummary {
if (typeof value !== 'object' || value === null) return false

const game = value as Record<string, unknown>
Expand All @@ -34,19 +34,22 @@ function IsGame(value: unknown): value is Game {
typeof game.initialprice === 'string' &&
typeof game.discount === 'string' &&
typeof game.img === 'string' &&
typeof game.genre === 'string' &&
typeof game.description === 'string'
typeof game.genre === 'string'
)
}

function IsGame(value: unknown): value is Game {
return IsGameSummary(value) && typeof (value as Game).description === 'string'
}

function IsCachedGames(value: unknown): value is CachedGames {
if (typeof value !== 'object' || value === null) return false

const cache = value as Record<string, unknown>
return (
typeof cache.fetchedAt === 'number' &&
Array.isArray(cache.games) &&
cache.games.every(IsGame)
cache.games.every(IsGameSummary)
)
}

Expand All @@ -66,47 +69,28 @@ function GameByIdCacheKey(appid: number): string {
return `game:v1:${appid}`
}

function ReadCachedGames(key: string): Game[] | null {
function ReadCachedGames(key: string): GameSummary[] | null {
const cache = ReadStored<CachedGames | null>(key, null, OrNull(IsCachedGames), 'local')
if (!cache) return null

const age = Date.now() - (IsCachedGames(cache) ? cache.fetchedAt : 0)
if (IsCachedGames(cache) && age >= 0 && age < CACHE_TTL_MS) {
const age = Date.now() - cache.fetchedAt
if (age >= 0 && age < CACHE_TTL_MS) {
return cache.games
}

RemoveStored(key, 'local')
return null
}

function WriteCachedGames(key: string, games: Game[]): void {
function WriteCachedGames(key: string, games: GameSummary[]): void {
WriteStored(key, { fetchedAt: Date.now(), games } satisfies CachedGames, 'local')
}

function FindCachedGameById(appid: number): Game | null {
const cachedGame = ReadCachedGames(GameByIdCacheKey(appid))?.find(
(game) => game.appid === appid
)
if (cachedGame) return cachedGame

try {
const storage = globalThis.localStorage
if (!storage) return null

// Collect keys first because readCachedGames may remove expired entries.
const cacheKeys = Array.from({ length: storage.length }, (_, index) =>
storage.key(index)
).filter((key): key is string => key !== null && key.startsWith(GAMES_CACHE_PREFIX))

for (const key of cacheKeys) {
const game = ReadCachedGames(key)?.find((candidate) => candidate.appid === appid)
if (game) return game
}
} catch (error) {
console.warn('Unable to search localStorage; fetching game from the database.', error)
}

return null
return cachedGame && IsGame(cachedGame) ? cachedGame : null
}

export async function GetGameById(appid: number): Promise<Game | null> {
Expand Down Expand Up @@ -153,7 +137,7 @@ async function FetchGamesFromDB(
limit: number,
offset: number,
options: GameQueryOptions = {}
): Promise<Game[]> {
): Promise<GameSummary[]> {
const cacheKey = GamesCacheKey(limit, offset, options)
const cachedGames = ReadCachedGames(cacheKey)
if (cachedGames) return cachedGames
Expand All @@ -172,7 +156,6 @@ async function FetchGamesFromDB(
discount
img
genre
description
}
}
`,
Expand All @@ -191,7 +174,7 @@ async function FetchGamesFromDB(
}

const { data, errors } = (await response.json()) as GraphQLResponse<{
games: Game[]
games: GameSummary[]
}>
if (errors?.length) throw new Error(errors[0].message)
if (!data) throw new Error('No data returned')
Expand Down
19 changes: 11 additions & 8 deletions Frontend/src/FrontendLogic/MainPageLogicFrontend.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Gql } from './LogicConnection'
import { type Game } from '../types/Game'
import { type GameSummary } from '../types/Game'
import { IsBoolean, IsInteger, IsString, ReadStored, WriteStored } from '../FrontendLogic/Storage'

export type MainPageGenreSection = 'top10' | 'discounts'

const GAME_FIELDS = `appid name price initialprice discount img genre description`
const GAME_FIELDS = `appid name price initialprice discount img genre`
const DISCOUNT_ONLY_KEY = 'GameStart:discountedOnlySearchpage'
const RECENT_REVIEW_KEY = 'GameStart:recentReviewCountMainpage'
const DEFAULT_REVIEW_COUNT = 3
Expand Down Expand Up @@ -68,21 +68,24 @@ export function PrepareDiscountGenreSearch(genre: string) {
}
}

export async function LoadTop3Games(): Promise<Game[]> {
const data = await Gql<{ top3Games: Game[] }>(`query { top3Games { ${GAME_FIELDS} } }`, {})
export async function LoadTop3Games(): Promise<GameSummary[]> {
const data = await Gql<{ top3Games: GameSummary[] }>(
`query { top3Games { ${GAME_FIELDS} } }`,
{}
)
return data.top3Games
}

export async function LoadTopGamesByGenre(genre: string): Promise<Game[]> {
const data = await Gql<{ topGamesByGenre: Game[] }>(
export async function LoadTopGamesByGenre(genre: string): Promise<GameSummary[]> {
const data = await Gql<{ topGamesByGenre: GameSummary[] }>(
`query ($genre: String!) { topGamesByGenre(genre: $genre) { ${GAME_FIELDS} } }`,
{ genre }
)
return data.topGamesByGenre
}

export async function LoadDiscountedGames(genre: string): Promise<Game[]> {
const data = await Gql<{ discountedGames: Game[] }>(
export async function LoadDiscountedGames(genre: string): Promise<GameSummary[]> {
const data = await Gql<{ discountedGames: GameSummary[] }>(
`query ($genre: String!) { discountedGames(genre: $genre) { ${GAME_FIELDS} } }`,
{ genre }
)
Expand Down
8 changes: 4 additions & 4 deletions Frontend/src/FrontendLogic/WishlistLogicFrontend.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { type Game } from '../types/Game'
import { type GameSummary } from '../types/Game'
import { Gql } from './LogicConnection'
import { IsString, ReadStored, WriteStored } from './Storage'

const WISHLIST_KEY = 'GameStart:sortOptionWishlist'

// Frontend function for calling backend to fetch wishlisted games of a user
export async function FetchWishlistFrontend(userId: number | null): Promise<Game[]> {
const data = await Gql<{ wishlist: Game[] }>(
export async function FetchWishlistFrontend(userId: number | null): Promise<GameSummary[]> {
const data = await Gql<{ wishlist: GameSummary[] }>(
`query($userId: Int!) {
wishlist(userId: $userId) {
appid name price initialprice discount img genre description
appid name price initialprice discount img genre
}
}`,
{ userId }
Expand Down
6 changes: 3 additions & 3 deletions Frontend/src/components/GenreGamesSection.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type Game } from '../types/Game'
import { type GameSummary } from '../types/Game'
import {
GetSavedMainPageGenre,
SaveMainPageGenre,
Expand All @@ -13,7 +13,7 @@ import { Link } from 'react-router-dom'

const NO_GAMES: PageGame[] = []

export function ToPageGame(game: Game): PageGame {
export function ToPageGame(game: GameSummary): PageGame {
const price = Number(game.price)
const salePercent = Number(game.discount)
const genres =
Expand All @@ -39,7 +39,7 @@ type GenreGamesSectionProps = {
genres: string[]
genresLoading: boolean
genresError?: string | null
loadGames: (genre: string) => Promise<Game[]>
loadGames: (genre: string) => Promise<GameSummary[]>
loadingText: string
emptyText: string
showSeeMore?: boolean
Expand Down
5 changes: 4 additions & 1 deletion Frontend/src/components/SearchPageControls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type { SelectChangeEvent } from '@mui/material'
import { Funnel, X } from 'lucide-react'

export type SortOption =
'' | 'discount-desc' | 'price-asc' | 'price-desc' | 'title-asc' | 'title-desc'
'' | 'title-asc' | 'title-desc' | 'rating-desc' | 'discount-desc' | 'price-asc' | 'price-desc'

interface SearchPageControlsProps {
searchValue: string
Expand Down Expand Up @@ -98,6 +98,9 @@ export default function SearchPageControls({
<MenuItem className="sortingOptionSearchpage" value="title-desc">
Title: Z to A
</MenuItem>
<MenuItem className="sortingOptionSearchpage" value="rating-desc">
Rating: high to low
</MenuItem>
<MenuItem className="sortingOptionSearchpage" value="discount-desc">
Discount: high to low
</MenuItem>
Expand Down
18 changes: 9 additions & 9 deletions Frontend/src/components/SearchPageResults.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { memo } from 'react'
import { Pagination } from '@mui/material'
import type { Game } from '../../../Backend/Steam'
import type { GameSummary } from '../types/Game'
import PassiveGameCard from './PassiveGameCard/PassiveGameCard'

const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: Game[] }) {
const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: GameSummary[] }) {
return (
<div className="games-grid-searchpage">
{games.map((game) => {
Expand All @@ -28,7 +28,7 @@ const SearchResultsGrid = memo(function SearchResultsGrid({ games }: { games: Ga
})

interface SearchPageResultsProps {
games: Game[]
games: GameSummary[]
error: string | null
isLoading: boolean
totalCount: number
Expand Down Expand Up @@ -56,11 +56,11 @@ export default function SearchPageResults({
return (
<>
<div className="searchResultsHeader">
{!error && totalCount > 0 && (
<p className="gamesFound">
{totalCount} {totalCount === 1 ? 'game' : 'games'} found
</p>
)}
<p className="gamesFound" role="status" aria-live="polite" aria-atomic="true">
{!error && totalCount > 0
? `${totalCount} ${totalCount === 1 ? 'game' : 'games'} found`
: ''}
</p>
<Pagination
className="pageinationSearchTop"
count={pageCount}
Expand All @@ -76,7 +76,7 @@ export default function SearchPageResults({
)}
{isLoading && games.length === 0 && <p className="searchMessage">Loading games...</p>}
{!error && !isLoading && games.length === 0 && (
<p className="searchMessage">No games found.</p>
<p className="searchMessage" role="status">No games found.</p>
)}
{games.length > 0 && <SearchResultsGrid games={games} />}
<Pagination
Expand Down
32 changes: 32 additions & 0 deletions Frontend/src/hooks/useSaveSearchPageState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useEffect } from 'react'
import {
SaveFilterMenuOpenSearchpage,
SaveFiltersSearchpage,
SavePageSearchpage,
SaveQuerySearchpage,
SaveSortOptionSearchpage
} from '../FrontendLogic/SearchPageLogicFrontend'

interface SearchPageState {
page: number
filters: string[]
sort: string
query: string
isFilterMenuOpen: boolean
}

export function useSaveSearchPageState({
page,
filters,
sort,
query,
isFilterMenuOpen
}: SearchPageState) {
useEffect(() => {
SavePageSearchpage(page)
SaveFiltersSearchpage(filters)
SaveSortOptionSearchpage(sort)
SaveQuerySearchpage(query)
SaveFilterMenuOpenSearchpage(isFilterMenuOpen)
}, [page, filters, sort, query, isFilterMenuOpen])
}
Loading