aboutsummaryrefslogtreecommitdiffstats
path: root/backend/src/routes/user.ts
blob: 3019da7dd66aa7fbf045b8bb9f1163618d7ad84a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// Routes about self (or users in general)
import express from 'express';
import { prisma } from '../config/db';

interface RecentPlayedGame {
  gameInternalName: string;
  timestamp: BigInt;
}

interface SafeGameCount {
  gameInternalName: string;
  formattedName: string;
  count: number;
}

export const handleMeRoute = async (req: express.Request, res: express.Response) => {
  try {
    const { userId } = req.query;
    if (!userId) {
      return res.status(400).json({ error: 'userId query parameter is required' });
    }
    const user = await prisma.user.findUniqueOrThrow({
      where: { id: parseInt(userId as string) },
      select: { id: true, username: true, isAdmin: true, bio: true }
    });
    const recentPlayedGames: RecentPlayedGame[] = await prisma.$queryRaw`
      SELECT *
      FROM (
        SELECT DISTINCT ON (s."gameInternalName")
          g."formattedName",
          s."timestamp",
          s."gameInternalName"
        FROM "Score" s
        INNER JOIN "Game" g ON g."internalName" = s."gameInternalName"
        WHERE s."userId" = ${parseInt(userId as string)}
        ORDER BY s."gameInternalName", s."timestamp" DESC
      ) sub
      ORDER BY sub."timestamp" DESC
      LIMIT 5;
    `;
    const scoreCountByGame: SafeGameCount[] = await prisma.$queryRaw`
      SELECT
        s."gameInternalName",
        g."formattedName",
        COUNT(*) as "count"
      FROM "Score" s
      INNER JOIN "Game" g ON g."internalName" = s."gameInternalName"
      WHERE s."userId" = ${parseInt(userId as string)}
      GROUP BY s."gameInternalName", g."formattedName"
    `;
    const safeGames= recentPlayedGames.map((game) => ({
      ...game,
      timestamp:
        typeof game.timestamp === "bigint"
          ? Number(game.timestamp)
          : game.timestamp,
    }));
    const safeScoreCountByGame = scoreCountByGame.map((game) => ({
      ...game,
      count: Number(game.count),
    }));
    const isAdmin = user.id === 1 || user.isAdmin;
    const { isAdmin: _, ...safeUser } = user;
    res.json({ user: safeUser, recentPlayedGames: safeGames, scoreCountByGame: safeScoreCountByGame, isAdmin });
  } catch (error) {
    console.error('Me endpoint error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
};

export const handleGetCurrentSession =  async (req: express.Request, res: express.Response) => {
  try {
    if (!req.session.userId) {
      return res.json({ authenticated: false });
    }

    const user = await prisma.user.findUnique({
      where: { id: req.session.userId },
      select: { id: true, username: true, isAdmin: true }
    });

    if (!user) {
      req.session.destroy((err) => {
        if (err) console.error('Session destroy error:', err);
      });
      return res.json({ authenticated: false });
    }

    res.json({
      authenticated: true,
      user
    });
  } catch (error) {
    console.error('Session check error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
}

export const handleGetScoresHeatmap = async (req: express.Request, res: express.Response) => {
  const { userId, gameInternalName } = req.query;
  if (!userId) {
    return res.status(400).json({ error: "Must specify userId to lookup parameters" });
  }
  try {
    const user = await prisma.user.findUnique({
      where: { id: parseInt(userId as string) },
      select: { id: true, username: true, isAdmin: true }
    });
    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }

    const oneYearAndOneDay = new Date(Date.now() - 365 * 24 * 60 * 60 * 1000);
    const unixMs = Math.floor(oneYearAndOneDay.getTime() / 1000);

    const scores = await prisma.score.findMany({
      where: {
        userId: parseInt(userId as string),
        timestamp: { gte: unixMs },
        ...(gameInternalName && { gameInternalName: gameInternalName as string })
      },
      orderBy: { timestamp: 'desc' },
      select: {
        timestamp: true
      }
    }).then(scores => scores.map(score => ({
      ...score,
      timestamp: Number(score.timestamp)
    })))

    res.json({
      "username": user.username,
      "isAdmin": user.isAdmin,
      scores
    });
  } catch (error) {
    console.error('Session check error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage