umami/pages/api/websites/index.ts

49 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-11-15 21:21:14 +00:00
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
2022-11-18 06:27:33 +00:00
import { uuid } from 'lib/crypto';
import { useAuth, useCors } from 'lib/middleware';
2022-11-15 21:21:14 +00:00
import { NextApiResponse } from 'next';
2022-11-18 06:27:33 +00:00
import { getRandomChars, methodNotAllowed, ok } from 'next-basics';
import { createWebsiteByUser, getAllWebsites, getWebsitesByUserId } from 'queries';
2022-11-15 21:21:14 +00:00
2022-11-18 06:46:05 +00:00
export interface WebsitesRequestQuery {
2022-11-15 21:21:14 +00:00
include_all?: boolean;
}
2022-11-18 06:46:05 +00:00
export interface WebsitesRequestBody {
2022-11-15 21:21:14 +00:00
name: string;
domain: string;
enableShareUrl: boolean;
}
export default async (
2022-11-18 06:46:05 +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);
2022-11-09 15:40:17 +00:00
const {
2022-11-09 20:03:24 +00:00
user: { id: userId, isAdmin },
2022-11-09 15:40:17 +00:00
} = req.auth;
2020-08-12 05:24:41 +00:00
if (req.method === 'GET') {
2022-11-02 22:45:47 +00:00
const { include_all } = req.query;
2020-09-11 06:55:29 +00:00
2022-11-08 19:55:02 +00:00
const websites =
2022-11-18 06:27:33 +00:00
isAdmin && include_all ? await getAllWebsites() : await getWebsitesByUserId(userId);
2020-08-12 05:24:41 +00:00
return ok(res, websites);
}
if (req.method === 'POST') {
2022-11-02 22:45:47 +00:00
const { name, domain, enableShareUrl } = req.body;
2022-10-12 20:11:44 +00:00
const shareId = enableShareUrl ? getRandomChars(8) : null;
2022-11-18 06:27:33 +00:00
const website = await createWebsiteByUser(userId, { id: uuid(), name, domain, shareId });
return ok(res, website);
}
2020-08-12 05:24:41 +00:00
return methodNotAllowed(res);
};