umami/pages/api/websites/index.ts

59 lines
1.3 KiB
TypeScript
Raw Normal View History

import { canCreateWebsite } from 'lib/auth';
2023-07-29 02:21:34 +02:00
import { uuid } from 'lib/crypto';
2022-11-18 07:27:33 +01:00
import { useAuth, useCors } from 'lib/middleware';
2023-08-10 22:26:33 +02:00
import { NextApiRequestQueryBody, SearchFilter, WebsiteSearchFilterType } from 'lib/types';
2022-11-15 22:21:14 +01:00
import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
import { createWebsite } from 'queries';
import userWebsites from 'pages/api/users/[id]/websites';
2022-11-15 22:21:14 +01:00
2023-08-10 22:26:33 +02:00
export interface WebsitesRequestQuery extends SearchFilter<WebsiteSearchFilterType> {}
2022-11-18 07:46:05 +01:00
export interface WebsitesRequestBody {
2022-11-15 22:21:14 +01:00
name: string;
domain: string;
2022-11-20 09:48:13 +01:00
shareId: string;
2022-11-15 22:21:14 +01:00
}
export default async (
2023-08-10 22:26:33 +02:00
req: NextApiRequestQueryBody<WebsitesRequestQuery, WebsitesRequestBody>,
2022-11-15 22:21:14 +01:00
res: NextApiResponse,
) => {
await useCors(req, res);
2020-08-12 07:24:41 +02:00
await useAuth(req, res);
2022-11-09 16:40:17 +01:00
const {
2022-11-22 01:44:42 +01:00
user: { id: userId },
2022-11-09 16:40:17 +01:00
} = req.auth;
2020-08-12 07:24:41 +02:00
if (req.method === 'GET') {
req.query.id = userId;
2023-08-10 22:26:33 +02:00
req.query.pageSize = 100;
2020-08-12 07:24:41 +02:00
return userWebsites(req, res);
2020-08-12 07:24:41 +02:00
}
if (req.method === 'POST') {
const { name, domain, shareId } = req.body;
2022-11-20 09:48:13 +01:00
if (!(await canCreateWebsite(req.auth))) {
return unauthorized(res);
}
const data: any = {
2022-11-20 09:48:13 +01:00
id: uuid(),
name,
domain,
shareId,
};
data.userId = userId;
2022-11-20 09:48:13 +01:00
const website = await createWebsite(data);
return ok(res, website);
}
2020-08-12 07:24:41 +02:00
return methodNotAllowed(res);
};