Skip to content
Merged
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
9 changes: 8 additions & 1 deletion Backend/resolvers/GameResolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ import {
} from '../logic/MainPageLogicBackend.ts'
import type { Game } from '../Steam.ts'

const NAME_GROUP = `CASE
WHEN g.game_name ~ '^[[:alpha:]]' THEN 0
WHEN g.game_name ~ '^[[:digit:]]' THEN 1
ELSE 2
END`

const SORT_SQL: Record<string, string> = {
'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': 'g.game_name ASC'
'title-asc': `${NAME_GROUP} ASC, LOWER(g.game_name) ASC`,
'title-desc': `${NAME_GROUP} DESC, LOWER(g.game_name) DESC`
}

function BuildGameFilter(search?: string | null, genres?: string[] | null, withRank = false) {
Expand Down
8 changes: 3 additions & 5 deletions Database/FillDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { pool } from '../Backend/DatabaseConnection.ts'

const FILE = path.join(process.cwd(), 'src', 'database', 'games.json')
const FILE = path.join(process.cwd(), 'Database', 'games.json')
const CHUNK = 500 // games per INSERT statement

async function FillDb() {
Expand All @@ -15,25 +15,23 @@ async function FillDb() {

await pool.query(
`INSERT INTO games (game_id, game_name, current_price, initial_price,
discount_percent, image_url, genre, description)
discount_percent, image_url, description)
SELECT appid,
name,
CASE WHEN price = 'Free' THEN 0 ELSE price::numeric END,
initialprice::numeric,
discount::int,
img,
genre,
description
FROM jsonb_to_recordset($1::jsonb)
AS g(appid int, name text, price text, initialprice text,
discount text, img text, genre text, description text)
discount text, img text, description text)
ON CONFLICT (game_id) DO UPDATE SET
game_name = EXCLUDED.game_name,
current_price = EXCLUDED.current_price,
initial_price = EXCLUDED.initial_price,
discount_percent = EXCLUDED.discount_percent,
image_url = EXCLUDED.image_url,
genre = EXCLUDED.genre,
description = EXCLUDED.description`,
[JSON.stringify(chunk)]
)
Expand Down
File renamed without changes.
File renamed without changes.
5 changes: 3 additions & 2 deletions Frontend/src/FrontendLogic/GameLogicFrontend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ interface GraphQLResponse<T> {
}

const CACHE_TTL_MS = 12 * 60 * 60 * 1000
const GAMES_CACHE_PREFIX = `games:v2:${encodeURIComponent(BACKEND_URL)}:`

interface CachedGames {
fetchedAt: number
Expand Down Expand Up @@ -49,7 +50,7 @@ export interface GameQueryOptions {
// Must include the filters, otherwise different filters would share the same cached page.
function GamesCacheKey(limit: number, offset: number, options: GameQueryOptions): string {
const { search = '', genres = [], sort = '' } = options
return `games:v1:${limit}:${offset}:${sort}:${search}:${genres.join('|')}`
return `${GAMES_CACHE_PREFIX}${limit}:${offset}:${sort}:${search}:${genres.join('|')}`
}

function GameByIdCacheKey(appid: number): string {
Expand Down Expand Up @@ -99,7 +100,7 @@ function FindCachedGameById(appid: number): Game | 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:v1:'))
).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)
Expand Down
37 changes: 37 additions & 0 deletions Frontend/src/css/SearchPage.css
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,40 @@
.searchError {
font-weight: 700;
}

.searchResultsHeader {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
align-self: center;
width: min(calc(100% - 32px), 1088px);
margin-top: 24px;
}

.gamesFound {
grid-column: 1;
margin: 0;
}

.pageinationSearchTop {
grid-column: 2;
justify-self: center;
max-width: 100%;
margin-top: 0;
}

@media (max-width: 690px) {
.searchResultsHeader {
row-gap: 8px;
}

.pageinationSearchTop {
grid-column: 2;
grid-row: 1;
}

.gamesFound {
grid-column: 1 / -1;
grid-row: 2;
}
}
35 changes: 25 additions & 10 deletions Frontend/src/pages/SearchPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,16 @@ import type { Game } from '../../../Backend/Steam'
import type { SelectChangeEvent } from '@mui/material'
import { X } from 'lucide-react'

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

const DEFAULT_SORT: SortOption = 'title-asc'
const SORT_OPTIONS: SortOption[] = ['title-asc', 'discount-desc', 'price-asc', 'price-desc']
const SORT_OPTIONS: SortOption[] = [
'title-asc',
'title-desc',
'discount-desc',
'price-asc',
'price-desc'
]
const GAMES_PER_PAGE = 12

const NO_GAMES: Game[] = []
Expand Down Expand Up @@ -233,6 +239,9 @@ export function SearchPage() {
<MenuItem className="sortingOptionSearchpage" value="title-asc">
Title: A to Z
</MenuItem>
<MenuItem className="sortingOptionSearchpage" value="title-desc">
Title: Z to A
</MenuItem>
<MenuItem className="sortingOptionSearchpage" value="discount-desc">
Discount: high to low
</MenuItem>
Expand Down Expand Up @@ -289,14 +298,20 @@ export function SearchPage() {
</Button>
</div>
)}
<Pagination
className="pageinationSearchTop"
count={pageCount}
page={page}
onChange={(_, value) => {
setPage(value)
}}
/>
<div className="searchResultsHeader">
{totalCount > 0 && (
<p className="gamesFound">
{totalCount} {totalCount === 1 ? 'game' : 'games'} found
</p>
)}

<Pagination
className="pageinationSearchTop"
count={pageCount}
page={page}
onChange={(_, value) => setPage(value)}
/>
</div>
{error && (
<p className="searchMessage searchError" role="alert">
Could not load games: {error}
Expand Down
30 changes: 25 additions & 5 deletions Frontend/src/tests/GameLogicFrontend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import FetchGamesFromDB, {
} from '../FrontendLogic/GameLogicFrontend'
import { BACKEND_URL } from '../FrontendLogic/LogicConnection'

const GAMES_CACHE_PREFIX = `games:v2:${encodeURIComponent(BACKEND_URL)}:`

function MockResponse(body: unknown, ok = true, status = 200): Response {
return {
ok,
Expand Down Expand Up @@ -119,7 +121,7 @@ describe('fetchGamesFromDB', () => {
expect(firstResult).toEqual([game])
expect(secondResult).toEqual([game])
expect(global.fetch).toHaveBeenCalledTimes(1)
expect(JSON.parse(values.get('games:v1:1:0:::') ?? '{}')).toEqual({
expect(JSON.parse(values.get(`${GAMES_CACHE_PREFIX}1:0:::`) ?? '{}')).toEqual({
fetchedAt: expect.any(Number),
games: [game]
})
Expand All @@ -135,14 +137,14 @@ describe('fetchGamesFromDB', () => {
await FetchGamesFromDB(1, 0, { genres: ['Action'] })

expect(global.fetch).toHaveBeenCalledTimes(2)
expect(values.has('games:v1:1:0:::Action')).toBe(true)
expect(values.has('games:v1:1:0:::')).toBe(true)
expect(values.has(`${GAMES_CACHE_PREFIX}1:0:::Action`)).toBe(true)
expect(values.has(`${GAMES_CACHE_PREFIX}1:0:::`)).toBe(true)
})

it('fetches fresh results when the cached games are at least 12 hours old', async () => {
const values = new Map<string, string>([
[
'games:v1:1:0:::',
`${GAMES_CACHE_PREFIX}1:0:::`,
JSON.stringify({
fetchedAt: Date.now() - 12 * 60 * 60 * 1000,
games: []
Expand All @@ -157,6 +159,21 @@ describe('fetchGamesFromDB', () => {
expect(global.fetch).toHaveBeenCalledTimes(1)
})

it('does not reuse cached results from the previous cache version', async () => {
const values = new Map([
[
'games:v1:1:0:title-desc::',
JSON.stringify({ fetchedAt: Date.now(), games: [game] })
]
])
StubLocalStorage(values)
global.fetch = vi.fn().mockResolvedValue(MockResponse({ data: { games: [] } }))

await expect(FetchGamesFromDB(1, 0, { sort: 'title-desc' })).resolves.toEqual([])

expect(global.fetch).toHaveBeenCalledOnce()
})

describe('getGameById', () => {
beforeEach(() => {
vi.restoreAllMocks()
Expand All @@ -165,7 +182,10 @@ describe('fetchGamesFromDB', () => {

it('returns a game from an existing page cache without fetching', async () => {
const values = new Map([
['games:v1:500:0:::', JSON.stringify({ fetchedAt: Date.now(), games: [game] })]
[
`${GAMES_CACHE_PREFIX}500:0:::`,
JSON.stringify({ fetchedAt: Date.now(), games: [game] })
]
])
StubLocalStorage(values)
global.fetch = vi.fn()
Expand Down
1 change: 1 addition & 0 deletions Frontend/src/tests/SearchPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ describe('SearchPage', () => {
})

it.each([
['Title: Z to A', 'title-desc'],
['Price: low to high', 'price-asc'],
['Price: high to low', 'price-desc'],
['Discount: high to low', 'discount-desc']
Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ You can also access application through the virtual machine by using this link:
| `npm run db:create` | Creates the database tables |
| `npm run db:fill` | Fills the database with games |
| `npm run db:fill:genres` | Fills the database with genres |
| `npm run server:local` | Starts the backend server using `.env.development` |
| `npm run db:create:local` | Creates the tables in your local database using `.env.development` |
| `npm run db:fill:local` | Fills your local database with games using `.env.development` |
| `npm run db:fill:genres:local` | Fills your local database with genres using `.env.development` |
| `npm run server:local` | Starts the backend server using `Frontend/.env.development` |
| `npm run db:create:local` | Creates the tables in your local database using `Frontend/.env.development` |
| `npm run db:fill:local` | Fills your local database with games using `Frontend/.env.development` |
| `npm run db:fill:genres:local` | Fills your local database with genres using `Frontend/.env.development` |

## Folder structure

Expand Down Expand Up @@ -368,7 +368,7 @@ If you don’t see the version after restarting your terminal, something has gon

When psql works, you can run: ```psql -h localhost -U USERNAME``` to access PostgreSQL. Username will be the username you created in the first step. When you have logged in you should see this:

Now you can run ```CREATE DATABASE t10db;``` to create a database for our project. Once this is done you have to set up the .env.development. This is the env file used for all the local shenanigans. There is a ```.env.development.example``` file already in the project, so you can just rename it to ```.env.development``` and use it.
Now you can run ```CREATE DATABASE t10db;``` to create a database for our project. Once this is done you have to set up ```Frontend/.env.development```. This is the env file used for all the local shenanigans. There is a ```Frontend/.env.development.example``` file already in the project, so you can copy it to ```Frontend/.env.development``` and use it.

```text
DB_HOST=localhost
Expand All @@ -389,7 +389,7 @@ Lucky for you, we have set up a few custom commands that should make this proces

In a separate terminal, run: ```npm run db:create:local```, to create all the empty tables.

Then run: ```npm run db:fill:local```, to fill the database with all the games and ```npm run db:fill:genres:local``` to fill the database with genres. The "local" parameter makes sure that the project uses the ```.env.development``` instead of the ```.env```.
Then run: ```npm run db:fill:local```, to fill the database with all the games and ```npm run db:fill:genres:local``` to fill the database with genres. The "local" parameter makes sure that the project uses ```Frontend/.env.development``` instead of ```.env```.

Once this is done running, you should be able to go into your database in the psql terminal, run: ```\c t10db```, to connect to the local database. In there you can run: ```SELECT COUNT(game_id) FROM games;``` and if everything has gone smoothly, you should see ```5334``` as the total amount of games.

Expand All @@ -399,7 +399,7 @@ Now you should be able to use the database.

To use the local database you have to have a local server running. This can be created by running ```npm run server:local```. Now that the database and server is up and running you should be able to run the project by running npm run dev as usual.

If you want to run the project with ```npm run dev``` using the VM backend after creating the ```.env.development```, you may have to uncomment or remove ```VITE_BACKEND_URL=http://localhost:3001/``` as the existence of this variable will cause the project to run on the local backend.
If you want to run the project with ```npm run dev``` using the VM backend after creating ```Frontend/.env.development```, you may have to uncomment or remove ```VITE_BACKEND_URL=http://localhost:3001/``` as the existence of this variable will cause the project to run on the local backend.

## Known issues

Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
"db:create": "node Database/CreateTables.ts",
"db:fill": "node Database/FillDb.ts",
"db:fill:genres":"node Database/FillGenres.ts",
"server:local": "node --env-file=.env.development Backend/Server.ts",
"db:create:local": "node --env-file=.env.development Database/CreateTables.ts",
"db:fill:local": "node --env-file=.env.development Database/FillDb.ts",
"db:fill:genres:local":"node --env-file=.env.development Database/FillGenres.ts"
"server:local": "node --env-file=Frontend/.env.development Backend/Server.ts",
"db:create:local": "node --env-file=Frontend/.env.development Database/CreateTables.ts",
"db:fill:local": "node --env-file=Frontend/.env.development Database/FillDb.ts",
"db:fill:genres:local":"node --env-file=Frontend/.env.development Database/FillGenres.ts"
},
"dependencies": {
"@apollo/server": "^5.5.1",
Expand Down