leaky-ships/leaky-ships/pages/api/game/join.ts
2023-07-11 19:25:44 +02:00

89 lines
2.2 KiB
TypeScript

import sendError from "@backend/sendError"
import sendResponse from "@backend/sendResponse"
import { rejectionErrors } from "@lib/backend/errors"
import getPinFromBody from "@lib/backend/getPinFromBody"
import logging from "@lib/backend/logging"
import prisma from "@lib/prisma"
import { GamePropsSchema } from "@lib/zodSchemas"
import type { NextApiRequest, NextApiResponse } from "next"
import { getServerSession } from "next-auth"
import { authOptions } from "../auth/[...nextauth]"
import { composeBody, gameSelects } from "./running"
export default async function join(
req: NextApiRequest,
res: NextApiResponse<GamePropsSchema>,
) {
const session = await getServerSession(req, res, authOptions)
const pin = await getPinFromBody(req, res)
if (!session?.user) {
return sendResponse(req, res, rejectionErrors.unauthorized)
}
const { email, id } = session.user
try {
const game = await prisma.game.findFirst({
where: {
gamePin: {
pin,
},
},
})
if (!game) {
return sendResponse(req, res, {
message: "Spiel existiert nicht",
statusCode: 404,
type: ["infoCyan"],
})
}
const games = await prisma.game.findMany({
where: {
NOT: {
state: "ended",
},
users: {
some: {
userId: id,
},
},
},
...gameSelects,
})
if (games.length) {
return sendResponse(req, res, {
message: "Spieler ist bereits in Spiel!",
redirectUrl: "/api/game/running",
type: ["infoCyan"],
})
}
const user_Game = await prisma.user_Game.create({
data: {
gameId: game.id,
userId: id,
index: 1,
},
select: {
game: gameSelects,
},
})
const body = composeBody(user_Game.game)
return sendResponse(req, res, {
message: `User <${email}> joined game: ${game.id}`,
body,
type: ["debug", "infoCyan"],
})
} catch (err: any) {
await logging(
"HERE".red + err.code + err.meta + err.message,
["error"],
req,
)
throw sendError(req, res, rejectionErrors.gameNotFound)
}
}