umami/pages/api/teams/index.ts

53 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-11-18 09:27:42 +01:00
import { Team } from '@prisma/client';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
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';
import { badRequest, methodNotAllowed, ok, unauthorized } from 'next-basics';
2022-11-18 09:27:42 +01:00
import { createTeam, getTeam, getTeamsByUserId } from 'queries';
export interface TeamsRequestBody {
name: string;
description: 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') {
const teams = await getTeamsByUserId(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(userId)) {
return unauthorized(res);
}
2022-11-18 09:27:42 +01:00
const { name } = req.body;
2022-11-20 09:48:13 +01:00
const team = await getTeam({ name });
2022-11-18 09:27:42 +01:00
2022-11-20 09:48:13 +01:00
if (team) {
2022-11-18 09:27:42 +01:00
return badRequest(res, 'Team already exists');
}
const created = await createTeam({
id: uuid(),
2022-11-18 09:27:42 +01:00
name,
});
return ok(res, created);
}
return methodNotAllowed(res);
};