2022-12-27 23:18:58 +00:00
|
|
|
import { canCreateWebsite } from 'lib/auth';
|
2023-07-23 20:18:01 +00:00
|
|
|
import { uuid } from 'next-basics';
|
2022-11-18 06:27:33 +00:00
|
|
|
import { useAuth, useCors } from 'lib/middleware';
|
2022-12-27 23:18:58 +00:00
|
|
|
import { NextApiRequestQueryBody } from 'lib/types';
|
2022-11-15 21:21:14 +00:00
|
|
|
import { NextApiResponse } from 'next';
|
2022-12-27 23:18:58 +00:00
|
|
|
import { methodNotAllowed, ok, unauthorized } from 'next-basics';
|
2022-12-07 02:36:41 +00:00
|
|
|
import { createWebsite, getUserWebsites } from 'queries';
|
2022-11-15 21:21:14 +00:00
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default async (
|
2023-02-08 00:29:25 +00:00
|
|
|
req: NextApiRequestQueryBody<any, WebsitesRequestBody>,
|
2022-11-15 21:21:14 +00:00
|
|
|
res: NextApiResponse,
|
|
|
|
|
) => {
|
2022-11-02 15:57:52 +00:00
|
|
|
await useCors(req, res);
|
2020-08-12 05:24:41 +00:00
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
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') {
|
2022-12-07 02:36:41 +00:00
|
|
|
const websites = await getUserWebsites(userId);
|
2020-08-12 05:24:41 +00:00
|
|
|
|
|
|
|
|
return ok(res, websites);
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-04 00:17:53 +00:00
|
|
|
if (req.method === 'POST') {
|
2023-04-14 03:57:22 +00:00
|
|
|
const { name, domain, shareId } = req.body;
|
2022-11-20 08:48:13 +00:00
|
|
|
|
2023-04-14 03:57:22 +00:00
|
|
|
if (!(await canCreateWebsite(req.auth))) {
|
2022-12-27 23:18:58 +00:00
|
|
|
return unauthorized(res);
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-28 23:43:22 +00:00
|
|
|
const data: any = {
|
2022-11-20 08:48:13 +00:00
|
|
|
id: uuid(),
|
|
|
|
|
name,
|
|
|
|
|
domain,
|
|
|
|
|
shareId,
|
|
|
|
|
};
|
|
|
|
|
|
2023-04-14 03:57:22 +00:00
|
|
|
data.userId = userId;
|
2022-11-20 08:48:13 +00:00
|
|
|
|
|
|
|
|
const website = await createWebsite(data);
|
2022-10-04 00:17:53 +00:00
|
|
|
|
|
|
|
|
return ok(res, website);
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-12 05:24:41 +00:00
|
|
|
return methodNotAllowed(res);
|
|
|
|
|
};
|