Skip to content

Commit

Permalink
Handle unique constraint violation error (#918)
Browse files Browse the repository at this point in the history
  • Loading branch information
Kiran K authored Jan 16, 2024
1 parent 51fc00f commit 152aa81
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 6 deletions.
9 changes: 8 additions & 1 deletion lib/zod/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
34 changes: 29 additions & 5 deletions pages/api/teams/[slug]/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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',
Expand Down

0 comments on commit 152aa81

Please sign in to comment.