66 lines
1.6 KiB
TypeScript
66 lines
1.6 KiB
TypeScript
import sendResponse from "@backend/sendResponse"
|
|
import { rejectionErrors } from "@lib/backend/errors"
|
|
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, getAnyRunningGame } from "./running"
|
|
|
|
export default async function create(
|
|
req: NextApiRequest,
|
|
res: NextApiResponse<GamePropsSchema>,
|
|
) {
|
|
const session = await getServerSession(req, res, authOptions)
|
|
|
|
if (!session?.user) {
|
|
return sendResponse(req, res, rejectionErrors.unauthorized)
|
|
}
|
|
const { email, id } = session.user
|
|
|
|
// Generate a random 4-digit code
|
|
const pin = Math.floor(Math.random() * 10000)
|
|
.toString()
|
|
.padStart(4, "0")
|
|
|
|
let created = false
|
|
|
|
let game = await getAnyRunningGame(id)
|
|
if (game) {
|
|
return sendResponse(req, res, {
|
|
redirectUrl: "/api/game/running",
|
|
message: "Running game already exists.",
|
|
})
|
|
} else {
|
|
game = await prisma.game.create({
|
|
data: {
|
|
gamePin: {
|
|
create: {
|
|
pin,
|
|
},
|
|
},
|
|
users: {
|
|
create: {
|
|
userId: id,
|
|
index: 0,
|
|
chats: {
|
|
create: {
|
|
event: "created",
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
...gameSelects,
|
|
})
|
|
}
|
|
|
|
const body = composeBody(game)
|
|
|
|
return sendResponse(req, res, {
|
|
message: `User <${email}> created game: ${game.id}`,
|
|
statusCode: created ? 201 : 200,
|
|
body,
|
|
type: ["debug", "infoCyan"],
|
|
})
|
|
}
|