diff --git a/lib/zod/schema.ts b/lib/zod/schema.ts index 9817cbeb5..749448cfc 100644 --- a/lib/zod/schema.ts +++ b/lib/zod/schema.ts @@ -30,7 +30,14 @@ export const updateTeamSchema = z.object({ { message: 'Enter a domain name in the format example.com', } - ), + ) + .transform((domain) => { + if (!domain) { + return null; + } + + return domain.trim().toLowerCase(); + }), }); export const createTeamSchema = z.object({ diff --git a/pages/api/teams/[slug]/index.ts b/pages/api/teams/[slug]/index.ts index 333c70739..98aca2af6 100644 --- a/pages/api/teams/[slug]/index.ts +++ b/pages/api/teams/[slug]/index.ts @@ -12,6 +12,7 @@ import { recordMetric } from '@/lib/metrics'; import { ApiError } from '@/lib/errors'; import env from '@/lib/env'; import { updateTeamSchema } from '@/lib/zod/schema'; +import { Prisma, Team } from '@prisma/client'; export default async function handler( req: NextApiRequest, @@ -65,11 +66,34 @@ const handlePUT = async (req: NextApiRequest, res: NextApiResponse) => { const { name, slug, domain } = updateTeamSchema.parse(req.body); - const updatedTeam = await updateTeam(user.team.slug, { - name, - slug, - domain, - }); + let updatedTeam: Team | null = null; + + try { + updatedTeam = await updateTeam(user.team.slug, { + name, + slug, + domain, + }); + } catch (error: any) { + if (error instanceof Prisma.PrismaClientKnownRequestError) { + if (error.code === 'P2002' && error.meta?.target) { + const target = error.meta.target as string[]; + + if (target.includes('slug')) { + throw new ApiError(409, 'This slug is already taken for a team.'); + } + + if (target.includes('domain')) { + throw new ApiError( + 409, + 'This domain is already associated with a team.' + ); + } + } + } + + throw error; + } sendAudit({ action: 'team.update',