2022-12-07 03:36:41 +01:00
|
|
|
import { Prisma } from '@prisma/client';
|
2022-12-28 00:18:58 +01:00
|
|
|
import { canCreateWebsite } from 'lib/auth';
|
2022-12-07 03:36:41 +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-12-07 03:36:41 +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';
|
|
|
|
|
|
|
|
export interface WebsitesRequestQuery {}
|
|
|
|
|
|
|
|
export interface WebsitesRequestBody {
|
|
|
|
name: string;
|
|
|
|
domain: string;
|
|
|
|
shareId: string;
|
|
|
|
teamId?: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<WebsitesRequestQuery, WebsitesRequestBody>,
|
|
|
|
res: NextApiResponse,
|
|
|
|
) => {
|
|
|
|
await useCors(req, res);
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
|
|
const {
|
|
|
|
user: { id: userId },
|
|
|
|
} = req.auth;
|
2023-01-25 16:42:46 +01:00
|
|
|
const { id } = req.query;
|
2022-12-07 03:36:41 +01:00
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2023-01-25 16:42:46 +01:00
|
|
|
const websites = await getUserWebsites(id as string);
|
2022-12-07 03:36:41 +01:00
|
|
|
|
|
|
|
return ok(res, websites);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'POST') {
|
|
|
|
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-07 03:36:41 +01:00
|
|
|
const data: Prisma.WebsiteUncheckedCreateInput = {
|
|
|
|
id: uuid(),
|
|
|
|
name,
|
|
|
|
domain,
|
|
|
|
shareId,
|
|
|
|
};
|
|
|
|
|
|
|
|
if (teamId) {
|
|
|
|
data.teamId = teamId;
|
|
|
|
} else {
|
|
|
|
data.userId = userId;
|
|
|
|
}
|
|
|
|
|
|
|
|
const website = await createWebsite(data);
|
|
|
|
|
|
|
|
return ok(res, website);
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|