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

62 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;
2022-11-18 07:46:05 +01:00
}
export default async (
req: NextApiRequestQueryBody<TeamRequestQuery, TeamRequestBody>,
res: NextApiResponse<Team>,
) => {
await useAuth(req, res);
const {
user: { id: userId },
} = req.auth;
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-07 03:36:41 +01:00
if (!(await canViewTeam(userId, 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') {
2022-11-20 09:48:13 +01:00
const { name } = req.body;
2022-11-18 07:46:05 +01:00
2022-12-07 03:36:41 +01:00
if (!(await canUpdateTeam(userId, 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-07 03:36:41 +01:00
if (!(await canDeleteTeam(userId, 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);
};