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

59 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-11-18 09:27:42 +01:00
import { Team } from '@prisma/client';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
2022-11-20 09:48:13 +01:00
import { allowQuery } from 'lib/auth';
import { UmamiApi } from 'lib/constants';
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-11-20 09:48:13 +01:00
if (!(await allowQuery(req, UmamiApi.AuthType.Team))) {
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-11-20 09:48:13 +01:00
if (!(await allowQuery(req, UmamiApi.AuthType.TeamOwner))) {
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-11-20 09:48:13 +01:00
if (!(await allowQuery(req, UmamiApi.AuthType.TeamOwner))) {
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);
};