diff --git a/lib/slugify.ts b/lib/slugify.ts new file mode 100644 index 00000000..a0a530ef --- /dev/null +++ b/lib/slugify.ts @@ -0,0 +1,5 @@ +export const slugify = (str: string) => { + return str.replace(/\s+/g, "-").toLowerCase(); +}; + +export default slugify; diff --git a/pages/api/teams.ts b/pages/api/teams.ts index 73a48bd8..b386832f 100644 --- a/pages/api/teams.ts +++ b/pages/api/teams.ts @@ -1,6 +1,7 @@ import type { NextApiRequest, NextApiResponse } from "next"; import prisma from "../../lib/prisma"; import { getSession } from "next-auth/client"; +import slugify from "@lib/slugify"; export default async function handler(req: NextApiRequest, res: NextApiResponse) { const session = await getSession({ req: req }); @@ -11,11 +12,22 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) } if (req.method === "POST") { - // TODO: Prevent creating a team with identical names? + 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." }); + } const createTeam = await prisma.team.create({ data: { name: req.body.name, + slug: slug, }, });