2022-11-18 09:27:42 +01:00
|
|
|
import { Team } from '@prisma/client';
|
|
|
|
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
|
2022-11-18 07:46:05 +01:00
|
|
|
import { useAuth } from 'lib/middleware';
|
|
|
|
import { NextApiResponse } from 'next';
|
2022-11-18 09:27:42 +01:00
|
|
|
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
|
|
|
|
import { deleteTeam, getTeam, updateTeam } from 'queries';
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
export interface TeamRequestQuery {
|
|
|
|
id: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface TeamRequestBody {
|
2022-11-18 09:27:42 +01:00
|
|
|
name?: string;
|
|
|
|
is_deleted?: boolean;
|
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, isAdmin },
|
|
|
|
} = req.auth;
|
|
|
|
const { id } = req.query;
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
|
|
|
if (id !== userId && !isAdmin) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
const user = await getTeam({ id });
|
|
|
|
|
|
|
|
return ok(res, user);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'POST') {
|
2022-11-18 09:27:42 +01:00
|
|
|
const { name, is_deleted: isDeleted } = req.body;
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
if (id !== userId && !isAdmin) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2022-11-18 09:27:42 +01:00
|
|
|
const updated = await updateTeam({ name, isDeleted }, { id });
|
2022-11-18 07:46:05 +01:00
|
|
|
|
|
|
|
return ok(res, updated);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'DELETE') {
|
|
|
|
if (id === userId) {
|
|
|
|
return badRequest(res, 'You cannot delete your own user.');
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!isAdmin) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
await deleteTeam(id);
|
|
|
|
|
|
|
|
return ok(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|