umami/pages/api/teams/index.ts

51 lines
1.1 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 { 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';
2023-02-02 03:39:54 +01:00
import { getRandomChars, methodNotAllowed, ok, unauthorized } from 'next-basics';
2022-12-07 03:36:41 +01:00
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 {
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') {
if (!(await canCreateTeam(req.auth))) {
return unauthorized(res);
}
2022-11-18 09:27:42 +01:00
const { name } = req.body;
const team = await createTeam(
{
id: uuid(),
name,
accessCode: getRandomChars(16),
},
2022-12-07 03:36:41 +01:00
userId,
);
2022-11-18 09:27:42 +01:00
2023-02-02 03:39:54 +01:00
return ok(res, team);
2022-11-18 09:27:42 +01:00
}
return methodNotAllowed(res);
};