2021-07-07 10:43:13 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
|
|
|
import prisma from "../../lib/prisma";
|
2021-09-03 20:51:21 +00:00
|
|
|
import { getSession } from "@lib/auth";
|
2021-08-13 19:50:11 +00:00
|
|
|
import slugify from "@lib/slugify";
|
2021-06-05 22:53:33 +00:00
|
|
|
|
|
|
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
2021-07-07 10:43:13 +00:00
|
|
|
const session = await getSession({ req: req });
|
2021-06-05 22:53:33 +00:00
|
|
|
|
|
|
|
if (!session) {
|
2021-07-07 10:43:13 +00:00
|
|
|
res.status(401).json({ message: "Not authenticated" });
|
2021-06-05 22:53:33 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === "POST") {
|
2021-08-13 19:50:11 +00:00
|
|
|
const slug = slugify(req.body.name);
|
|
|
|
|
|
|
|
const nameCollisions = await prisma.team.count({
|
|
|
|
where: {
|
|
|
|
OR: [{ name: req.body.name }, { slug: slug }],
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (nameCollisions > 0) {
|
|
|
|
return res.status(409).json({ errorCode: "TeamNameCollision", message: "Team name already take." });
|
|
|
|
}
|
2021-06-07 15:12:00 +00:00
|
|
|
|
2021-06-05 22:53:33 +00:00
|
|
|
const createTeam = await prisma.team.create({
|
|
|
|
data: {
|
|
|
|
name: req.body.name,
|
2021-08-13 19:50:11 +00:00
|
|
|
slug: slug,
|
2021-06-05 22:53:33 +00:00
|
|
|
},
|
|
|
|
});
|
|
|
|
|
2021-07-01 09:47:12 +00:00
|
|
|
await prisma.membership.create({
|
2021-06-05 22:53:33 +00:00
|
|
|
data: {
|
|
|
|
teamId: createTeam.id,
|
|
|
|
userId: session.user.id,
|
2021-07-07 10:43:13 +00:00
|
|
|
role: "OWNER",
|
2021-06-05 22:53:33 +00:00
|
|
|
accepted: true,
|
2021-07-07 10:43:13 +00:00
|
|
|
},
|
2021-06-05 22:53:33 +00:00
|
|
|
});
|
|
|
|
|
2021-07-07 10:43:13 +00:00
|
|
|
return res.status(201).json({ message: "Team created" });
|
2021-06-05 22:53:33 +00:00
|
|
|
}
|
|
|
|
|
2021-07-07 10:43:13 +00:00
|
|
|
res.status(404).json({ message: "Team not found" });
|
2021-06-05 22:53:33 +00:00
|
|
|
}
|