2022-11-18 09:27:42 +01:00
|
|
|
import { Team } from '@prisma/client';
|
2022-12-07 03:36:41 +01:00
|
|
|
import { NextApiRequestQueryBody } from 'lib/types';
|
2022-12-02 05:53:37 +01:00
|
|
|
import { canDeleteTeam, canUpdateTeam, canViewTeam } from 'lib/auth';
|
2022-11-18 07:46:05 +01:00
|
|
|
import { useAuth } from 'lib/middleware';
|
|
|
|
import { NextApiResponse } from 'next';
|
2022-11-20 09:48:13 +01:00
|
|
|
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
|
2022-11-18 09:27:42 +01:00
|
|
|
import { deleteTeam, getTeam, updateTeam } from 'queries';
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
export interface TeamRequestQuery {
|
|
|
|
id: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface TeamRequestBody {
|
2022-11-20 09:48:13 +01:00
|
|
|
name: string;
|
2022-11-18 07:46:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<TeamRequestQuery, TeamRequestBody>,
|
|
|
|
res: NextApiResponse<Team>,
|
|
|
|
) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
2022-11-20 09:48:13 +01:00
|
|
|
const { id: teamId } = req.query;
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2022-12-28 00:18:58 +01:00
|
|
|
if (!(await canViewTeam(req.auth, teamId))) {
|
2022-11-18 07:46:05 +01:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
2022-12-02 05:53:37 +01:00
|
|
|
|
2022-11-20 09:48:13 +01:00
|
|
|
const user = await getTeam({ id: teamId });
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
return ok(res, user);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'POST') {
|
2022-11-20 09:48:13 +01:00
|
|
|
const { name } = req.body;
|
2022-11-18 07:46:05 +01:00
|
|
|
|
2022-12-28 00:18:58 +01:00
|
|
|
if (!(await canUpdateTeam(req.auth, teamId))) {
|
2022-11-20 09:48:13 +01:00
|
|
|
return unauthorized(res, 'You must be the owner of this team.');
|
2022-11-18 07:46:05 +01:00
|
|
|
}
|
|
|
|
|
2022-11-20 09:48:13 +01:00
|
|
|
const updated = await updateTeam({ name }, { id: teamId });
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
return ok(res, updated);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'DELETE') {
|
2022-12-28 00:18:58 +01:00
|
|
|
if (!(await canDeleteTeam(req.auth, teamId))) {
|
2022-11-20 09:48:13 +01:00
|
|
|
return unauthorized(res, 'You must be the owner of this team.');
|
2022-11-18 07:46:05 +01:00
|
|
|
}
|
|
|
|
|
2022-11-20 09:48:13 +01:00
|
|
|
await deleteTeam(teamId);
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
return ok(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|