Files
pichunt/server/api/hunt/[huntId]/join.post.ts
T
2025-08-21 00:17:01 +02:00

71 lines
1.3 KiB
TypeScript

import { useValidatedBody, useValidatedParams, z, zh } from 'h3-zod';
import prisma from '~~/lib/prisma';
export default defineEventHandler(async (event) => {
const { huntId } = await useValidatedParams(
event,
z.object({
huntId: zh.numAsString
})
);
const user = await requireUserSession(event);
const userId = user.user.id;
const existingTeam = await prisma.huntTeam.findFirst({
select: {
id: true
},
where: {
huntId,
OR: [
{
ownerId: userId
},
{
members: {
some: {
memberId: userId
}
}
}
]
}
});
if (existingTeam) {
throw createError({ status: 409, statusText: 'You already have a team!' });
}
const { team: teamId, password } = await useValidatedBody(
event,
z.object({
team: z.number().min(1),
password: z.string().max(256)
})
);
const team = await prisma.huntTeam.findUnique({
where: {
huntId,
id: teamId,
password
},
select: { id: true }
});
if (!team) {
throw createError({
status: 404,
statusText: 'Team not found or invalid password!'
});
}
await prisma.teamMember.create({
data: {
memberId: userId,
teamId
}
});
return { success: true };
});