2023-02-02 03:39:54 +01:00
|
|
|
import { Team } from '@prisma/client';
|
|
|
|
import { NextApiRequestQueryBody } from 'lib/types';
|
|
|
|
import { useAuth } from 'lib/middleware';
|
|
|
|
import { NextApiResponse } from 'next';
|
|
|
|
import { methodNotAllowed, ok, notFound } from 'next-basics';
|
2023-03-30 01:02:14 +02:00
|
|
|
import { createTeamUser, getTeam, getTeamUser } from 'queries';
|
2023-02-02 03:39:54 +01:00
|
|
|
import { ROLES } from 'lib/constants';
|
|
|
|
|
2023-03-09 21:42:12 +01:00
|
|
|
export interface TeamsJoinRequestBody {
|
2023-02-02 03:39:54 +01:00
|
|
|
accessCode: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
2023-03-09 21:42:12 +01:00
|
|
|
req: NextApiRequestQueryBody<any, TeamsJoinRequestBody>,
|
|
|
|
res: NextApiResponse<Team>,
|
2023-02-02 03:39:54 +01:00
|
|
|
) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
|
|
if (req.method === 'POST') {
|
|
|
|
const { accessCode } = req.body;
|
|
|
|
|
|
|
|
const team = await getTeam({ accessCode });
|
|
|
|
|
|
|
|
if (!team) {
|
|
|
|
return notFound(res, 'message.team-not-found');
|
|
|
|
}
|
|
|
|
|
2023-03-30 01:02:14 +02:00
|
|
|
const teamUser = await getTeamUser(team.id, req.auth.user.id);
|
|
|
|
|
|
|
|
if (teamUser) {
|
|
|
|
return methodNotAllowed(res, 'message.team-already-member');
|
|
|
|
}
|
|
|
|
|
2023-02-02 03:39:54 +01:00
|
|
|
await createTeamUser(req.auth.user.id, team.id, ROLES.teamMember);
|
|
|
|
|
|
|
|
return ok(res, team);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|