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 { canCreateTeam } from 'lib/auth';
|
2022-11-18 09:27:42 +01:00
|
|
|
import { uuid } from 'lib/crypto';
|
|
|
|
import { useAuth } from 'lib/middleware';
|
|
|
|
import { NextApiResponse } from 'next';
|
2022-12-07 03:36:41 +01:00
|
|
|
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
|
|
|
|
import { createTeam, getUserTeams } from 'queries';
|
|
|
|
|
2022-11-18 09:27:42 +01:00
|
|
|
export interface TeamsRequestBody {
|
|
|
|
name: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<any, TeamsRequestBody>,
|
|
|
|
res: NextApiResponse<Team[] | Team>,
|
|
|
|
) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
|
|
const {
|
2022-12-02 05:53:37 +01:00
|
|
|
user: { id: userId },
|
2022-11-18 09:27:42 +01:00
|
|
|
} = req.auth;
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2022-12-07 03:36:41 +01:00
|
|
|
const teams = await getUserTeams(userId);
|
2022-11-18 09:27:42 +01:00
|
|
|
|
2022-11-20 09:48:13 +01:00
|
|
|
return ok(res, teams);
|
2022-11-18 09:27:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'POST') {
|
2022-12-07 03:36:41 +01:00
|
|
|
if (!(await canCreateTeam(userId))) {
|
2022-12-02 05:53:37 +01:00
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2022-11-18 09:27:42 +01:00
|
|
|
const { name } = req.body;
|
|
|
|
|
|
|
|
const created = await createTeam({
|
2022-12-02 05:53:37 +01:00
|
|
|
id: uuid(),
|
2022-11-18 09:27:42 +01:00
|
|
|
name,
|
2022-12-07 03:36:41 +01:00
|
|
|
userId,
|
2022-11-18 09:27:42 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
return ok(res, created);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|