umami/pages/api/teams/[id]/index.ts

61 lines
1.4 KiB
TypeScript
Raw Normal View History

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';
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;
2023-01-06 07:56:36 +01:00
accessCode: 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') {
if (!(await canViewTeam(req.auth, teamId))) {
2022-11-18 07:46:05 +01:00
return unauthorized(res);
}
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') {
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
}
2023-01-06 07:56:36 +01:00
const { name, accessCode } = req.body;
const data = { name, accessCode };
const updated = await updateTeam(data, { id: teamId });
2022-11-18 07:46:05 +01:00
return ok(res, updated);
}
if (req.method === 'DELETE') {
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);
};