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