prevent duplicate team names
This commit is contained in:
parent
60a4b8b29e
commit
216a7c0c48
2 changed files with 18 additions and 1 deletions
5
lib/slugify.ts
Normal file
5
lib/slugify.ts
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
export const slugify = (str: string) => {
|
||||||
|
return str.replace(/\s+/g, "-").toLowerCase();
|
||||||
|
};
|
||||||
|
|
||||||
|
export default slugify;
|
|
@ -1,6 +1,7 @@
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
import prisma from "../../lib/prisma";
|
import prisma from "../../lib/prisma";
|
||||||
import { getSession } from "next-auth/client";
|
import { getSession } from "next-auth/client";
|
||||||
|
import slugify from "@lib/slugify";
|
||||||
|
|
||||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const session = await getSession({ req: req });
|
const session = await getSession({ req: req });
|
||||||
|
@ -11,11 +12,22 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.method === "POST") {
|
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({
|
const createTeam = await prisma.team.create({
|
||||||
data: {
|
data: {
|
||||||
name: req.body.name,
|
name: req.body.name,
|
||||||
|
slug: slug,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue