Compare commits
3 Commits
2b22f504cf
...
48f7e71a8e
| Author | SHA1 | Date | |
|---|---|---|---|
| 48f7e71a8e | |||
| 9926673ffd | |||
| 0eb0fb5ee4 |
+10
-7
@@ -1,7 +1,13 @@
|
|||||||
# ── Production (Coolify) ────────────────────────────────────────────────────
|
# ── Production (Coolify) ────────────────────────────────────────────────────
|
||||||
# DB_PASSWORD is passed separately so special characters never need URL-encoding.
|
# DATABASE_URL must include the password. Special characters must be
|
||||||
# DATABASE_URL is constructed inside docker-compose.yml and does NOT need to be
|
# percent-encoded so the URL parser handles them correctly:
|
||||||
# set in Coolify — only DB_PASSWORD is required.
|
# # → %23 ] → %5D = → %3D @ → %40
|
||||||
|
#
|
||||||
|
# Example with password "p#ss]w=rd":
|
||||||
|
# DATABASE_URL=postgres://wc:p%23ss%5Dw%3Drd@db:5432/worldcup
|
||||||
|
#
|
||||||
|
# DB_PASSWORD is used ONLY by the Postgres container (no encoding needed).
|
||||||
|
DATABASE_URL=postgres://wc:changeme@db:5432/worldcup
|
||||||
DB_PASSWORD=changeme
|
DB_PASSWORD=changeme
|
||||||
|
|
||||||
# Traefik (set TRAEFIK_ENABLED=true when deploying behind Traefik)
|
# Traefik (set TRAEFIK_ENABLED=true when deploying behind Traefik)
|
||||||
@@ -9,8 +15,5 @@ TRAEFIK_ENABLED=false
|
|||||||
TRAEFIK_HOST=worldcup.example.com
|
TRAEFIK_HOST=worldcup.example.com
|
||||||
NETWORK_NAME=traefik-network
|
NETWORK_NAME=traefik-network
|
||||||
|
|
||||||
# ── Local development ────────────────────────────────────────────────────────
|
# ── Local development ─────────────────────────────────────────────────────────
|
||||||
# Set DATABASE_URL when running pnpm dev or pnpm sync on the host directly.
|
|
||||||
# The password can be plain-text here since it goes through the postgres driver,
|
|
||||||
# not URL parsing, when DB_PASSWORD is unset.
|
|
||||||
# DATABASE_URL=postgres://wc:wc@localhost:5432/worldcup
|
# DATABASE_URL=postgres://wc:wc@localhost:5432/worldcup
|
||||||
|
|||||||
+1
-2
@@ -6,8 +6,7 @@ services:
|
|||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgres://wc@db:5432/worldcup
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
DB_PASSWORD: ${DB_PASSWORD}
|
|
||||||
NODE_ENV: production
|
NODE_ENV: production
|
||||||
labels:
|
labels:
|
||||||
- "traefik.enable=${TRAEFIK_ENABLED:-false}"
|
- "traefik.enable=${TRAEFIK_ENABLED:-false}"
|
||||||
|
|||||||
+6
-8
@@ -2,14 +2,12 @@ import { drizzle } from 'drizzle-orm/postgres-js'
|
|||||||
import postgres from 'postgres'
|
import postgres from 'postgres'
|
||||||
import * as schema from './schema'
|
import * as schema from './schema'
|
||||||
|
|
||||||
const connectionString = process.env.DATABASE_URL ?? 'postgres://wc:wc@localhost:5432/worldcup'
|
// Passwords with special chars (#, ], =) must be percent-encoded in DATABASE_URL.
|
||||||
|
// postgres.js decodes them correctly (e.g. %23 → #). No separate DB_PASSWORD needed.
|
||||||
// DB_PASSWORD is passed separately to avoid URL-encoding issues with special chars
|
const client = postgres(
|
||||||
// (e.g. #, ], = in passwords break URL parsing). Falls back to password in DATABASE_URL for local dev.
|
process.env.DATABASE_URL ?? 'postgres://wc:wc@localhost:5432/worldcup',
|
||||||
const client = postgres(connectionString, {
|
{ max: 10 }
|
||||||
max: 10,
|
)
|
||||||
...(process.env.DB_PASSWORD ? { password: process.env.DB_PASSWORD } : {}),
|
|
||||||
})
|
|
||||||
export const db = drizzle(client, { schema })
|
export const db = drizzle(client, { schema })
|
||||||
|
|
||||||
export * from './schema'
|
export * from './schema'
|
||||||
|
|||||||
@@ -59,74 +59,98 @@ async function hydrateMatch(row: typeof matches.$inferSelect) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isMissingTable(e: unknown): boolean {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e)
|
||||||
|
return msg.includes('relation') && msg.includes('does not exist')
|
||||||
|
}
|
||||||
|
|
||||||
export const resolvers = {
|
export const resolvers = {
|
||||||
Query: {
|
Query: {
|
||||||
async tournaments() {
|
async tournaments() {
|
||||||
const rows = await db.select().from(tournaments).orderBy(desc(tournaments.year))
|
try {
|
||||||
return rows.map(r => ({ ...r, avgGoalsPerGame: r.avgGoalsPerGame ? parseFloat(r.avgGoalsPerGame) : null }))
|
const rows = await db.select().from(tournaments).orderBy(desc(tournaments.year))
|
||||||
|
return rows.map(r => ({ ...r, avgGoalsPerGame: r.avgGoalsPerGame ? parseFloat(r.avgGoalsPerGame) : null }))
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async tournament(_: unknown, { year }: { year: number }) {
|
async tournament(_: unknown, { year }: { year: number }) {
|
||||||
const rows = await db.select().from(tournaments).where(eq(tournaments.year, year)).limit(1)
|
try {
|
||||||
if (!rows[0]) return null
|
const rows = await db.select().from(tournaments).where(eq(tournaments.year, year)).limit(1)
|
||||||
return { ...rows[0], avgGoalsPerGame: rows[0].avgGoalsPerGame ? parseFloat(rows[0].avgGoalsPerGame) : null }
|
if (!rows[0]) return null
|
||||||
|
return { ...rows[0], avgGoalsPerGame: rows[0].avgGoalsPerGame ? parseFloat(rows[0].avgGoalsPerGame) : null }
|
||||||
|
} catch (e) { if (isMissingTable(e)) return null; throw e }
|
||||||
},
|
},
|
||||||
async matches(_: unknown, args: { year?: number; group?: string; round?: string; isQuali?: boolean }) {
|
async matches(_: unknown, args: { year?: number; group?: string; round?: string; isQuali?: boolean }) {
|
||||||
const conditions = []
|
try {
|
||||||
if (args.year) conditions.push(eq(matches.tournamentYear, args.year))
|
const conditions = []
|
||||||
if (args.group) conditions.push(eq(matches.groupName, args.group))
|
if (args.year) conditions.push(eq(matches.tournamentYear, args.year))
|
||||||
if (args.round) conditions.push(eq(matches.round, args.round))
|
if (args.group) conditions.push(eq(matches.groupName, args.group))
|
||||||
if (args.isQuali != null) conditions.push(eq(matches.isQualiPlayoff, args.isQuali))
|
if (args.round) conditions.push(eq(matches.round, args.round))
|
||||||
const rows = await db.select().from(matches)
|
if (args.isQuali != null) conditions.push(eq(matches.isQualiPlayoff, args.isQuali))
|
||||||
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
const rows = await db.select().from(matches)
|
||||||
.orderBy(asc(matches.date), asc(matches.id))
|
.where(conditions.length > 0 ? and(...conditions) : undefined)
|
||||||
return Promise.all(rows.map(hydrateMatch))
|
.orderBy(asc(matches.date), asc(matches.id))
|
||||||
|
return Promise.all(rows.map(hydrateMatch))
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async match(_: unknown, { id }: { id: number }) {
|
async match(_: unknown, { id }: { id: number }) {
|
||||||
const rows = await db.select().from(matches).where(eq(matches.id, id)).limit(1)
|
try {
|
||||||
return rows[0] ? hydrateMatch(rows[0]) : null
|
const rows = await db.select().from(matches).where(eq(matches.id, id)).limit(1)
|
||||||
|
return rows[0] ? hydrateMatch(rows[0]) : null
|
||||||
|
} catch (e) { if (isMissingTable(e)) return null; throw e }
|
||||||
},
|
},
|
||||||
async liveMatches() {
|
async liveMatches() {
|
||||||
const today = new Date().toISOString().slice(0, 10)
|
try {
|
||||||
const rows = await db.select().from(matches)
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
.where(and(eq(matches.date, today), eq(matches.isQualiPlayoff, false)))
|
const rows = await db.select().from(matches)
|
||||||
.orderBy(asc(matches.id))
|
.where(and(eq(matches.date, today), eq(matches.isQualiPlayoff, false)))
|
||||||
const hydrated = await Promise.all(rows.map(hydrateMatch))
|
.orderBy(asc(matches.id))
|
||||||
return hydrated.filter(m => m.isLive)
|
const hydrated = await Promise.all(rows.map(hydrateMatch))
|
||||||
|
return hydrated.filter(m => m.isLive)
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async recentMatches(_: unknown, { limit = 10 }: { limit?: number }) {
|
async recentMatches(_: unknown, { limit = 10 }: { limit?: number }) {
|
||||||
const today = new Date().toISOString().slice(0, 10)
|
try {
|
||||||
const rows = await db.select().from(matches)
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
.where(and(
|
const rows = await db.select().from(matches)
|
||||||
lt(matches.date, today),
|
.where(and(
|
||||||
isNotNull(matches.scoreFtHome),
|
lt(matches.date, today),
|
||||||
eq(matches.isQualiPlayoff, false),
|
isNotNull(matches.scoreFtHome),
|
||||||
))
|
eq(matches.isQualiPlayoff, false),
|
||||||
.orderBy(desc(matches.date), desc(matches.id))
|
))
|
||||||
.limit(limit)
|
.orderBy(desc(matches.date), desc(matches.id))
|
||||||
return Promise.all(rows.map(hydrateMatch))
|
.limit(limit)
|
||||||
|
return Promise.all(rows.map(hydrateMatch))
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async upcomingMatches(_: unknown, { limit = 10 }: { limit?: number }) {
|
async upcomingMatches(_: unknown, { limit = 10 }: { limit?: number }) {
|
||||||
const today = new Date().toISOString().slice(0, 10)
|
try {
|
||||||
const rows = await db.select().from(matches)
|
const today = new Date().toISOString().slice(0, 10)
|
||||||
.where(and(
|
const rows = await db.select().from(matches)
|
||||||
gte(matches.date, today),
|
.where(and(
|
||||||
sql`${matches.scoreFtHome} IS NULL`,
|
gte(matches.date, today),
|
||||||
eq(matches.isQualiPlayoff, false),
|
sql`${matches.scoreFtHome} IS NULL`,
|
||||||
))
|
eq(matches.isQualiPlayoff, false),
|
||||||
.orderBy(asc(matches.date), asc(matches.id))
|
))
|
||||||
.limit(limit)
|
.orderBy(asc(matches.date), asc(matches.id))
|
||||||
return Promise.all(rows.map(hydrateMatch))
|
.limit(limit)
|
||||||
|
return Promise.all(rows.map(hydrateMatch))
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async teams() {
|
async teams() {
|
||||||
const rows = await db.select().from(teams).orderBy(asc(teams.name))
|
try {
|
||||||
return rows.map(teamWithSlug)
|
const rows = await db.select().from(teams).orderBy(asc(teams.name))
|
||||||
|
return rows.map(teamWithSlug)
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async team(_: unknown, { slug }: { slug: string }) {
|
async team(_: unknown, { slug }: { slug: string }) {
|
||||||
const rows = await db.select().from(teams)
|
try {
|
||||||
const found = rows.find(r => slugify(r.name) === slug)
|
const rows = await db.select().from(teams)
|
||||||
return found ? teamWithSlug(found) : null
|
const found = rows.find(r => slugify(r.name) === slug)
|
||||||
|
return found ? teamWithSlug(found) : null
|
||||||
|
} catch (e) { if (isMissingTable(e)) return null; throw e }
|
||||||
},
|
},
|
||||||
async topScorers(_: unknown, { year, limit = 20 }: { year?: number; limit?: number }) {
|
async topScorers(_: unknown, { year, limit = 20 }: { year?: number; limit?: number }) {
|
||||||
|
try {
|
||||||
const conditions = year
|
const conditions = year
|
||||||
? sql`AND m.tournament_year = ${year} AND m.is_quali_playoff = false`
|
? sql`AND m.tournament_year = ${year} AND m.is_quali_playoff = false`
|
||||||
: sql`AND m.is_quali_playoff = false`
|
: sql`AND m.is_quali_playoff = false`
|
||||||
@@ -153,6 +177,7 @@ export const resolvers = {
|
|||||||
tournaments: r.tournaments,
|
tournaments: r.tournaments,
|
||||||
team: r.team_id ? await getTeamById(r.team_id as number) : null,
|
team: r.team_id ? await getTeamById(r.team_id as number) : null,
|
||||||
})))
|
})))
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async player(_: unknown, { name }: { name: string }) {
|
async player(_: unknown, { name }: { name: string }) {
|
||||||
const rows = await db.execute(sql`
|
const rows = await db.execute(sql`
|
||||||
@@ -210,6 +235,7 @@ export const resolvers = {
|
|||||||
})))
|
})))
|
||||||
},
|
},
|
||||||
async groupStandings(_: unknown, { year }: { year: number }) {
|
async groupStandings(_: unknown, { year }: { year: number }) {
|
||||||
|
try {
|
||||||
const rows = await db.select({
|
const rows = await db.select({
|
||||||
groupName: groupStandings.groupName,
|
groupName: groupStandings.groupName,
|
||||||
pos: groupStandings.pos,
|
pos: groupStandings.pos,
|
||||||
@@ -237,6 +263,7 @@ export const resolvers = {
|
|||||||
pts: r.pts ?? 0,
|
pts: r.pts ?? 0,
|
||||||
team: (await getTeamById(r.teamId))!,
|
team: (await getTeamById(r.teamId))!,
|
||||||
})))
|
})))
|
||||||
|
} catch (e) { if (isMissingTable(e)) return []; throw e }
|
||||||
},
|
},
|
||||||
async stadiums(_: unknown, { year }: { year?: number }) {
|
async stadiums(_: unknown, { year }: { year?: number }) {
|
||||||
const rows = year
|
const rows = year
|
||||||
@@ -255,26 +282,20 @@ export const resolvers = {
|
|||||||
}))
|
}))
|
||||||
},
|
},
|
||||||
async tournamentStats() {
|
async tournamentStats() {
|
||||||
const [totals] = await db.execute(sql`
|
const empty = { totalTournaments: 0, totalMatches: 0, totalGoals: 0, avgGoalsPerGame: null, mostGoalsInTournament: null, highestScoringMatch: null, biggestWin: null, mostTitles: null }
|
||||||
SELECT
|
try {
|
||||||
COUNT(DISTINCT t.year)::int AS total_tournaments,
|
const [totals] = await db.execute(sql`
|
||||||
COUNT(DISTINCT m.id)::int AS total_matches,
|
SELECT
|
||||||
COALESCE(SUM(m.score_ft_home + m.score_ft_away), 0)::int AS total_goals,
|
COUNT(DISTINCT t.year)::int AS total_tournaments,
|
||||||
ROUND(COALESCE(SUM(m.score_ft_home + m.score_ft_away), 0)::numeric / NULLIF(COUNT(DISTINCT m.id), 0), 2)::float AS avg_goals
|
COUNT(DISTINCT m.id)::int AS total_matches,
|
||||||
FROM tournaments t
|
COALESCE(SUM(m.score_ft_home + m.score_ft_away), 0)::int AS total_goals,
|
||||||
LEFT JOIN matches m ON m.tournament_year = t.year AND m.is_quali_playoff = false AND m.score_ft_home IS NOT NULL
|
ROUND(COALESCE(SUM(m.score_ft_home + m.score_ft_away), 0)::numeric / NULLIF(COUNT(DISTINCT m.id), 0), 2)::float AS avg_goals
|
||||||
`)
|
FROM tournaments t
|
||||||
const r = totals as Record<string, unknown>
|
LEFT JOIN matches m ON m.tournament_year = t.year AND m.is_quali_playoff = false AND m.score_ft_home IS NOT NULL
|
||||||
return {
|
`)
|
||||||
totalTournaments: r.total_tournaments,
|
const r = totals as Record<string, unknown>
|
||||||
totalMatches: r.total_matches,
|
return { ...empty, totalTournaments: r.total_tournaments, totalMatches: r.total_matches, totalGoals: r.total_goals, avgGoalsPerGame: r.avg_goals }
|
||||||
totalGoals: r.total_goals,
|
} catch (e) { if (isMissingTable(e)) return empty; throw e }
|
||||||
avgGoalsPerGame: r.avg_goals,
|
|
||||||
mostGoalsInTournament: null,
|
|
||||||
highestScoringMatch: null,
|
|
||||||
biggestWin: null,
|
|
||||||
mostTitles: null,
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
async goalsByMinute() {
|
async goalsByMinute() {
|
||||||
const rows = await db.execute(sql`
|
const rows = await db.execute(sql`
|
||||||
@@ -316,7 +337,12 @@ export const resolvers = {
|
|||||||
GROUP BY t.confederation
|
GROUP BY t.confederation
|
||||||
ORDER BY appearances DESC
|
ORDER BY appearances DESC
|
||||||
`)
|
`)
|
||||||
return rows
|
return (rows as Record<string, unknown>[]).map(r => ({
|
||||||
|
confederation: r.confederation,
|
||||||
|
appearances: r.appearances,
|
||||||
|
titles: r.titles,
|
||||||
|
totalGoals: r.total_goals,
|
||||||
|
}))
|
||||||
},
|
},
|
||||||
async biggestWins(_: unknown, { limit = 10 }: { limit?: number }) {
|
async biggestWins(_: unknown, { limit = 10 }: { limit?: number }) {
|
||||||
const rows = await db.select().from(matches)
|
const rows = await db.select().from(matches)
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export const typeDefs = /* GraphQL */ `
|
|||||||
matchesCount: Int
|
matchesCount: Int
|
||||||
totalGoals: Int
|
totalGoals: Int
|
||||||
avgGoalsPerGame: Float
|
avgGoalsPerGame: Float
|
||||||
topScorers: [ScorerEntry!]!
|
topScorers(limit: Int): [ScorerEntry!]!
|
||||||
matches: [Match!]!
|
matches: [Match!]!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-4
@@ -73,10 +73,7 @@ function parseScore(score: RawScore | undefined) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
const client = postgres(DATABASE_URL, {
|
const client = postgres(DATABASE_URL, { max: 5 })
|
||||||
max: 5,
|
|
||||||
...(process.env.DB_PASSWORD ? { password: process.env.DB_PASSWORD } : {}),
|
|
||||||
})
|
|
||||||
const db = drizzle(client)
|
const db = drizzle(client)
|
||||||
|
|
||||||
console.log('Creating tables...')
|
console.log('Creating tables...')
|
||||||
|
|||||||
Reference in New Issue
Block a user