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
File renamed without changes.
94 changes: 94 additions & 0 deletions Backend/Schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
export const typeDefs = `#graphql
type Game {
appid: Int!
name: String
price: String
initialprice: String
discount: String
img: String
genre: String
description: String
}
type User {
id: Int!
email: String!
username: String!
token: String!
}
type Profile {
username: String!
description: String
setup: String
favouriteGame: Int
}
type GameOption {
appid: Int!
name: String!
}
input ProfileInput {
description: String
setup: String
favouriteGame: Int
}
type Review {
id: Int!
gameId: Int!
userId: Int
reviewer: String!
rating: Int!
text: String!
gameName: String
}
type Friend {
id: Int!
username: String!
description: String
setup: String
favouriteGame: Game
}
type Query {
games(
limit: Int = 500
offset: Int = 0
search: String
genres: [String!]
sort: String
): [Game!]!
wishlist(userId: Int!): [Game!]!
game(appid: Int!): Game
genres: [String!]!
profile(userId: Int!): Profile
gameOptions: [GameOption!]!
totalGameCount(
search: String
genres: [String!]
): Int!
top3Games: [Game!]!
topGamesByGenre(genre: String!): [Game!]!
discountedGames(genre: String!): [Game!]!
reviews(gameId: Int!, userId: Int): [Review!]!
recentReviews(limit: Int = 10): [Review!]!
friends(userId: Int!): [Friend!]!
friendWishlist(userId: Int!, friendId: Int!): [Game!]!
myFriendId(userId: Int!): String
}
type Mutation {
addToWishlist(userId: Int!, gameId: Int!): Boolean!
removeFromWishlist(userId: Int!, gameId: Int!): Boolean!
signup(username: String!, email: String!, password: String!): User!
signin(email: String!, password: String!): User!
updateProfile(userId: Int!, input: ProfileInput!): Profile!
createReview(userId: Int!, gameId: Int!, rating: Int!, text: String!): Review!
updateReview(reviewId: Int!, userId: Int!, rating: Int!, text: String!): Review!
deleteReview(reviewId: Int!, userId: Int!): Boolean!
addFriend(userId: Int!, friendCode: String!): Friend!
}
`
16 changes: 16 additions & 0 deletions Backend/Server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'
import { typeDefs } from './Schema.ts'
import { resolvers } from './resolvers/index.ts'

const server = new ApolloServer({ typeDefs, resolvers })
const { url } = await startStandaloneServer(server, {
listen: { host: process.env.HOST ?? '127.0.0.1', port: 3001 },
context: async ({ req }) => ({
token: req.headers.authorization?.replace(/^Bearer /, '') ?? null
})
})
console.log(
`Database: ${process.env.DB_USER}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`
)
console.log(`GraphQL server ready at ${url}`)
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GraphQLError } from 'graphql'
import { pool } from './DbConnection.ts'
import { pool } from '../DatabaseConnection.ts'

export interface Friend {
id: number
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pool } from './DbConnection.ts'
import { pool } from '../DatabaseConnection.ts'

export async function FetchGenres(): Promise<string[]> {
const { rows } = await pool.query(`SELECT genre_name FROM genres ORDER BY genre_name`)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { pool } from './DbConnection.ts'
import { type Game } from './Steam.ts'
import { REVIEW_SCORE_JOIN } from './Reviews.ts'
import { GAME_COLUMNS } from './GameColumns.ts'
import { pool } from '../DatabaseConnection.ts'
import { type Game } from '../Steam.ts'
import { REVIEW_SCORE_JOIN } from './ReviewsLogicBackend.ts'
import { GAME_COLUMNS } from '../types/GameColumns.ts'

const ORDER_BY_REVIEW_SCORE = `
rs.review_score DESC NULLS LAST,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { GraphQLError } from 'graphql'
import { pool } from './DbConnection.ts'
import { SETUP_OPTIONS } from '../types/SetupOptions.ts'
import { pool } from '../DatabaseConnection.ts'
import { SETUP_OPTIONS } from '../../Frontend/src/types/SetupOptions.ts'

const MAX_DESCRIPTION_LENGTH = 500

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { pool } from './DbConnection.ts'
import type { Review } from '../types/Review.ts'
import { pool } from '../DatabaseConnection.ts'
import type { Review } from '../../Frontend/src/types/Review.ts'

const REVIEW_COLUMNS = `
r.review_id AS id,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GraphQLError } from 'graphql'
import { pool } from './DbConnection.ts'
import { pool } from '../DatabaseConnection.ts'
import { randomBytes, randomInt } from 'crypto'
import bcrypt from 'bcrypt'

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { pool } from './DbConnection.ts'
import { pool } from '../DatabaseConnection.ts'

export async function AddToWishlist(
userId: number,
Expand Down
71 changes: 71 additions & 0 deletions Backend/resolvers/FriendResolvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { GraphQLError } from 'graphql'
import { pool } from '../DatabaseConnection.ts'
import { GAME_COLUMNS } from '../GameColumns.ts'
import { AddFriend, AreFriends, GetFriendId, GetFriends } from '../FriendLogicBackend.ts'
import type { Game } from '../Steam.ts'
import { RequireUser } from '../UserLogicBackend.ts'
import type { GraphQLContext } from './types.ts'

export const friendQueryResolvers = {
friends: async (
_parent: unknown,
{ userId }: { userId: number },
{ token }: GraphQLContext
) => {
await RequireUser(token, userId)
return GetFriends(userId)
},

friendWishlist: async (
_parent: unknown,
{ userId, friendId }: { userId: number; friendId: number },
{ token }: GraphQLContext
): Promise<Game[]> => {
await RequireUser(token, userId)
if (!(await AreFriends(userId, friendId))) {
throw new GraphQLError('You are not friends with this user.', {
extensions: { code: 'FORBIDDEN' }
})
}
const { rows } = await pool.query(
`SELECT ${GAME_COLUMNS}
FROM wishlist w
JOIN games g ON g.game_id = w.game_id
WHERE w.user_id = $1
ORDER BY g.game_name`,
[friendId]
)
return rows
},

myFriendId: async (
_parent: unknown,
{ userId }: { userId: number },
{ token }: GraphQLContext
) => {
await RequireUser(token, userId)
return GetFriendId(userId)
}
}

export const friendTypeResolvers = {
favouriteGame: async (friend: { favouriteGameId: number | null }): Promise<Game | null> => {
if (!friend.favouriteGameId) return null
const { rows } = await pool.query(
`SELECT ${GAME_COLUMNS} FROM games g WHERE g.game_id = $1`,
[friend.favouriteGameId]
)
return rows[0] ?? null
}
}

export const friendMutationResolvers = {
addFriend: async (
_parent: unknown,
{ userId, friendCode }: { userId: number; friendCode: string },
{ token }: GraphQLContext
) => {
await RequireUser(token, userId)
return AddFriend(userId, friendCode)
}
}
131 changes: 131 additions & 0 deletions Backend/resolvers/GameResolvers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { pool } from '../DatabaseConnection.ts'
import { FetchGenres } from '../Genres.ts'
import { GAME_COLUMNS } from '../GameColumns.ts'
import {
FetchDiscountedGames,
FetchTop10GamesPerGenre,
FetchTop3Games
} from '../MainPageLogicBackend.ts'
import type { Game } from '../Steam.ts'

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'
}

function BuildGameFilter(search?: string | null, genres?: string[] | null, withRank = false) {
const conditions: string[] = []
const params: unknown[] = []
let rank = ''

if (search?.trim()) {
const term = search.trim()

params.push(`%${term}%`)
conditions.push(`g.game_name ILIKE $${params.length}`)

if (withRank) {
const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
params.push(`^${escaped}\\M`)
const startIdx = params.length
params.push(`\\m${escaped}\\M`)
const wordIdx = params.length

rank = `CASE
WHEN g.game_name ~* $${startIdx} THEN 0
WHEN g.game_name ~* $${wordIdx} THEN 1
ELSE 2
END`
}
}

if (genres?.length) {
params.push(genres)
conditions.push(
`NOT EXISTS (
SELECT 1 FROM unnest($${params.length}::text[]) AS wanted(name)
WHERE NOT EXISTS (
SELECT 1 FROM genretogame gg
JOIN genres ge ON ge.genre_id = gg.genre_id
WHERE gg.game_id = g.game_id AND ge.genre_name = wanted.name
)
)`
)
}

return {
where: conditions.length ? `WHERE ${conditions.join(' AND ')}` : '',
params,
rank
}
}

export const gameQueryResolvers = {
games: async (
_parent: unknown,
{
limit,
offset,
search,
genres,
sort
}: {
limit: number
offset: number
search?: string | null
genres?: string[] | null
sort?: string | null
}
): Promise<Game[]> => {
const safeLimit = Math.min(Math.max(limit, 0), 500)
const safeOffset = Math.max(offset, 0)
const { where, params, rank } = BuildGameFilter(search, genres, true)

const orderBy = [SORT_SQL[sort ?? ''], rank, 'g.game_id'].filter(Boolean).join(', ')

const { rows } = await pool.query(
`SELECT ${GAME_COLUMNS}
FROM games g
${where}
ORDER BY ${orderBy}
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
[...params, safeLimit, safeOffset]
)
return rows
},

totalGameCount: async (
_parent: unknown,
{ search, genres }: { search?: string | null; genres?: string[] | null }
): Promise<number> => {
const { where, params } = BuildGameFilter(search, genres)
const { rows } = await pool.query(`SELECT COUNT(*) AS count FROM games g ${where}`, params)
return Number(rows[0].count)
},

game: async (_parent: unknown, { appid }: { appid: number }): Promise<Game | null> => {
const { rows } = await pool.query(
`SELECT ${GAME_COLUMNS}
FROM games g
WHERE g.game_id = $1`,
[appid]
)
return rows[0] ?? null
},

genres: () => FetchGenres(),

gameOptions: async () => {
const { rows } = await pool.query(
`SELECT game_id AS appid, game_name AS name FROM games ORDER BY game_name`
)
return rows
},

top3Games: () => FetchTop3Games(),
topGamesByGenre: (_parent: unknown, { genre }: { genre: string }) =>
FetchTop10GamesPerGenre(genre),
discountedGames: (_parent: unknown, { genre }: { genre: string }) => FetchDiscountedGames(genre)
}
Loading