umami/src/pages/api/teams/index.ts

69 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-11-18 08:27:42 +00:00
import { Team } from '@prisma/client';
import { canCreateTeam } from 'lib/auth';
2023-07-29 00:21:34 +00:00
import { uuid } from 'lib/crypto';
2023-08-20 05:23:15 +00:00
import { useAuth, useValidate } from 'lib/middleware';
import { NextApiRequestQueryBody, SearchFilter } from 'lib/types';
2023-09-22 07:59:00 +00:00
import { pageInfo } from 'lib/schema';
2022-11-18 08:27:42 +00:00
import { NextApiResponse } from 'next';
2023-02-02 02:39:54 +00:00
import { getRandomChars, methodNotAllowed, ok, unauthorized } from 'next-basics';
2023-08-10 20:26:33 +00:00
import { createTeam, getTeamsByUserId } from 'queries';
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
2022-12-07 02:36:41 +00:00
export interface TeamsRequestQuery extends SearchFilter {}
2023-08-20 05:23:15 +00:00
export interface TeamsRequestBody {
2022-11-18 08:27:42 +00:00
name: string;
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
2023-09-22 07:59:00 +00:00
...pageInfo,
2023-08-20 05:23:15 +00:00
}),
POST: yup.object().shape({
name: yup.string().max(50).required(),
}),
};
2022-11-18 08:27:42 +00:00
export default async (
2023-08-10 20:26:33 +00:00
req: NextApiRequestQueryBody<TeamsRequestQuery, TeamsRequestBody>,
2022-11-18 08:27:42 +00:00
res: NextApiResponse<Team[] | Team>,
) => {
await useAuth(req, res);
2023-09-30 03:24:48 +00:00
await useValidate(schema, req, res);
2023-08-20 05:23:15 +00:00
2022-11-18 08:27:42 +00:00
const {
user: { id: userId },
2022-11-18 08:27:42 +00:00
} = req.auth;
if (req.method === 'GET') {
2023-09-22 07:59:00 +00:00
const { page, query } = req.query;
2022-11-18 08:27:42 +00:00
2023-09-06 19:52:08 +00:00
const results = await getTeamsByUserId(userId, {
page,
2023-09-22 07:59:00 +00:00
query,
2023-09-06 19:52:08 +00:00
});
2023-08-10 20:26:33 +00:00
return ok(res, results);
2022-11-18 08:27:42 +00:00
}
if (req.method === 'POST') {
if (!(await canCreateTeam(req.auth))) {
return unauthorized(res);
}
2022-11-18 08:27:42 +00:00
const { name } = req.body;
const team = await createTeam(
{
id: uuid(),
name,
accessCode: getRandomChars(16),
},
2022-12-07 02:36:41 +00:00
userId,
);
2022-11-18 08:27:42 +00:00
2023-02-02 02:39:54 +00:00
return ok(res, team);
2022-11-18 08:27:42 +00:00
}
return methodNotAllowed(res);
};