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

79 lines
1.8 KiB
TypeScript
Raw Normal View History

import { canCreateWebsite } 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, useCors, useValidate } from 'lib/middleware';
2023-08-10 20:26:33 +00:00
import { NextApiRequestQueryBody, SearchFilter, WebsiteSearchFilterType } from 'lib/types';
2022-11-15 21:21:14 +00:00
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { createWebsite } from 'queries';
import userWebsites from 'pages/api/users/[id]/websites';
2023-08-20 05:23:15 +00:00
import * as yup from 'yup';
import { getFilterValidation } from 'lib/yup';
2022-11-15 21:21:14 +00:00
2023-08-10 20:26:33 +00:00
export interface WebsitesRequestQuery extends SearchFilter<WebsiteSearchFilterType> {}
2022-11-18 06:46:05 +00:00
export interface WebsitesRequestBody {
2022-11-15 21:21:14 +00:00
name: string;
domain: string;
2022-11-20 08:48:13 +00:00
shareId: string;
2022-11-15 21:21:14 +00:00
}
2023-08-20 05:23:15 +00:00
const schema = {
GET: yup.object().shape({
...getFilterValidation(/All|Name|Domain/i),
}),
POST: yup.object().shape({
name: yup.string().max(100).required(),
domain: yup.string().max(500).required(),
shareId: yup.string().max(50),
}),
};
2022-11-15 21:21:14 +00:00
export default async (
2023-08-10 20:26:33 +00:00
req: NextApiRequestQueryBody<WebsitesRequestQuery, WebsitesRequestBody>,
2022-11-15 21:21:14 +00:00
res: NextApiResponse,
) => {
await useCors(req, res);
2020-08-12 05:24:41 +00:00
await useAuth(req, res);
2023-08-20 05:23:15 +00:00
req.yup = schema;
await useValidate(req, res);
2020-08-12 05:24:41 +00:00
2022-11-09 15:40:17 +00:00
const {
2022-11-22 00:44:42 +00:00
user: { id: userId },
2022-11-09 15:40:17 +00:00
} = req.auth;
2020-08-12 05:24:41 +00:00
if (req.method === 'GET') {
2023-08-30 22:23:08 +00:00
if (!req.query.id) {
req.query.id = userId;
}
if (!req.query.pageSize) {
req.query.pageSize = 100;
}
2020-08-12 05:24:41 +00:00
2023-08-20 05:23:15 +00:00
return userWebsites(req as any, res);
2020-08-12 05:24:41 +00:00
}
if (req.method === 'POST') {
const { name, domain, shareId } = req.body;
2022-11-20 08:48:13 +00:00
if (!(await canCreateWebsite(req.auth))) {
return unauthorized(res);
}
const data: any = {
2022-11-20 08:48:13 +00:00
id: uuid(),
name,
domain,
shareId,
};
data.userId = userId;
2022-11-20 08:48:13 +00:00
const website = await createWebsite(data);
return ok(res, website);
}
2020-08-12 05:24:41 +00:00
return methodNotAllowed(res);
};