Skip to content

Commit 484587d

Browse files
committed
chore: Add game normalizing functions to DB
1 parent 72fac97 commit 484587d

2 files changed

Lines changed: 13 additions & 5 deletions

File tree

src/database/games.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { toId } from '@/utils/toId';
1111

1212
import type { Log as ScrabbleLog } from '@/ps/games/scrabble/logs';
1313
import type { WinCtx as ScrabbleWinCtx } from '@/ps/games/scrabble/types';
14-
import type { Player } from '@/ps/games/types';
14+
import type { BaseLog, Player } from '@/ps/games/types';
1515

1616
const schema = new mongoose.Schema<GameModel>({
1717
id: {
@@ -80,11 +80,19 @@ export interface GameModel {
8080
}
8181
const model = mongoose.model('game', schema, 'games', { overwriteModels: true });
8282

83+
export type NormalizedGame = Omit<GameModel, 'players' | 'log'> & { players: Record<string, Player>; log: BaseLog[] };
84+
8385
export async function uploadGame(game: GameModel): Promise<GameModel | null> {
8486
if (!IS_ENABLED.DB) return null;
8587
return model.create(game);
8688
}
8789

90+
// Hydrate logStrings into log objects
91+
export function normalizeGame(game: HydratedDocument<GameModel>): NormalizedGame {
92+
const serializable = 'toJSON' in game ? game.toJSON()! : game;
93+
return { ...serializable, log: serializable.log.map(entry => JSON.parse(entry)) };
94+
}
95+
8896
export async function getGameById(gameType: string, gameId: string): Promise<HydratedDocument<GameModel> | null> {
8997
if (!IS_ENABLED.DB) return null;
9098
const id = gameId.toUpperCase().replace(/^#?/, '#');

src/web/api/[game]/[gameId].ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { getGameById } from '@/database/games';
1+
import { getGameById, normalizeGame } from '@/database/games';
22
import { IS_ENABLED } from '@/enabled';
33
import { Games } from '@/ps/games';
44
import { WebError } from '@/utils/webError';
@@ -10,9 +10,9 @@ export const handler: RequestHandler = async (req, res, next) => {
1010
const { game: gameType, gameId } = req.params as { game: string; gameId: string };
1111
if (!Object.keys(Games).includes(gameType)) return next();
1212
try {
13-
const game = await getGameById(gameType, gameId);
14-
const serializable = game!.toJSON();
15-
res.json({ ...serializable, log: serializable.log.map(entry => JSON.parse(entry)) });
13+
const record = (await getGameById(gameType, gameId))!;
14+
const game = normalizeGame(record);
15+
res.json(game);
1616
} catch (err: unknown) {
1717
if (err instanceof Error) throw new WebError(err.message, 404);
1818
}

0 commit comments

Comments
 (0)