umami/src/pages/api/teams/[id]/websites/index.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-09-22 07:59:00 +00:00
import * as yup from 'yup';
2024-01-26 19:28:16 +00:00
import { canCreateTeamWebsite, canViewTeam } from 'lib/auth';
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';
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
2024-01-30 08:10:25 +00:00
import { createWebsite, getTeamWebsites } from 'queries';
2024-01-26 19:28:16 +00:00
import { uuid } from 'lib/crypto';
2022-11-18 08:27:42 +00:00
export interface TeamWebsiteRequestQuery extends SearchFilter {
2022-11-18 08:27:42 +00:00
id: string;
}
export interface TeamWebsiteRequestBody {
2024-01-26 19:28:16 +00:00
name: string;
domain: string;
shareId: string;
2022-11-18 08:27:42 +00:00
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
id: yup.string().uuid().required(),
2023-09-22 07:59:00 +00:00
...pageInfo,
2023-08-20 05:23:15 +00:00
}),
POST: yup.object().shape({
2024-01-26 19:28:16 +00:00
name: yup.string().max(100).required(),
domain: yup.string().max(500).required(),
shareId: yup.string().max(50).nullable(),
2023-08-20 05:23:15 +00:00
}),
};
2022-11-18 08:27:42 +00:00
export default async (
req: NextApiRequestQueryBody<TeamWebsiteRequestQuery, TeamWebsiteRequestBody>,
res: NextApiResponse,
) => {
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 { id: teamId } = req.query;
if (req.method === 'GET') {
2023-01-25 15:42:46 +00:00
if (!(await canViewTeam(req.auth, teamId))) {
2022-11-20 08:48:13 +00:00
return unauthorized(res);
}
2023-10-16 00:59:19 +00:00
const { page, query, pageSize } = req.query;
2024-01-30 08:10:25 +00:00
const websites = await getTeamWebsites(teamId, {
2023-10-16 00:59:19 +00:00
page,
query,
pageSize: +pageSize || undefined,
});
2022-11-18 08:27:42 +00:00
2022-12-07 02:36:41 +00:00
return ok(res, websites);
2022-11-18 08:27:42 +00:00
}
2024-01-26 19:28:16 +00:00
if (req.method === 'POST') {
if (!(await canCreateTeamWebsite(req.auth, teamId))) {
return unauthorized(res);
}
const { name, domain, shareId } = req.body;
const website = await createWebsite({ id: uuid(), name, domain, shareId });
return ok(res, website);
}
2022-11-18 08:27:42 +00:00
return methodNotAllowed(res);
};