umami/pages/api/teams/index.ts

54 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-11-18 09:27:42 +01:00
import { Team } from '@prisma/client';
import { canCreateTeam } from 'lib/auth';
2023-07-29 02:21:34 +02:00
import { uuid } from 'lib/crypto';
2022-11-18 09:27:42 +01:00
import { useAuth } from 'lib/middleware';
2023-08-10 22:26:33 +02:00
import { NextApiRequestQueryBody, SearchFilter, TeamSearchFilterType } from 'lib/types';
2022-11-18 09:27:42 +01:00
import { NextApiResponse } from 'next';
2023-02-02 03:39:54 +01:00
import { getRandomChars, methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-08-10 22:26:33 +02:00
import { createTeam, getTeamsByUserId } from 'queries';
2022-12-07 03:36:41 +01:00
2023-08-10 22:26:33 +02:00
export interface TeamsRequestQuery extends SearchFilter<TeamSearchFilterType> {}
export interface TeamsRequestBody extends SearchFilter<TeamSearchFilterType> {
2022-11-18 09:27:42 +01:00
name: string;
}
export default async (
2023-08-10 22:26:33 +02:00
req: NextApiRequestQueryBody<TeamsRequestQuery, TeamsRequestBody>,
2022-11-18 09:27:42 +01:00
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') {
2023-08-10 22:26:33 +02:00
const { page, filter, pageSize } = req.query;
2022-11-18 09:27:42 +01:00
2023-08-10 22:26:33 +02:00
const results = await getTeamsByUserId(userId, { page, filter, pageSize: +pageSize || null });
return ok(res, results);
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);
};