umami/pages/api/websites/[id]/index.ts

67 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-11-19 03:49:58 +01:00
import { Website } from 'interface/api/models';
import { NextApiRequestQueryBody } from 'interface/api/nextApi';
import { allowQuery } from 'lib/auth';
2022-11-19 03:49:58 +01:00
import { UmamiApi } from 'lib/constants';
import { useAuth, useCors } from 'lib/middleware';
2022-11-19 03:49:58 +01:00
import { NextApiResponse } from 'next';
2022-11-20 09:48:13 +01:00
import { methodNotAllowed, ok, serverError, unauthorized, badRequest } from 'next-basics';
2022-11-02 23:45:47 +01:00
import { deleteWebsite, getWebsite, updateWebsite } from 'queries';
2022-11-18 07:46:05 +01:00
export interface WebsiteRequestQuery {
2022-11-15 22:21:14 +01:00
id: string;
}
2022-11-18 07:46:05 +01:00
export interface WebsiteRequestBody {
2022-11-15 22:21:14 +01:00
name: string;
domain: string;
shareId: string;
2022-11-20 09:48:13 +01:00
userId?: string;
teamId?: string;
2022-11-15 22:21:14 +01:00
}
export default async (
2022-11-18 07:46:05 +01:00
req: NextApiRequestQueryBody<WebsiteRequestQuery, WebsiteRequestBody>,
2022-11-15 22:21:14 +01:00
res: NextApiResponse<Website | any>,
) => {
2022-10-12 22:11:44 +02:00
await useCors(req, res);
await useAuth(req, res);
2022-11-02 23:45:47 +01:00
const { id: websiteId } = req.query;
2022-11-19 03:49:58 +01:00
if (!(await allowQuery(req, UmamiApi.AuthType.Website))) {
2022-10-12 22:11:44 +02:00
return unauthorized(res);
}
2022-10-12 22:11:44 +02:00
if (req.method === 'GET') {
2022-11-02 23:45:47 +01:00
const website = await getWebsite({ id: websiteId });
return ok(res, website);
}
if (req.method === 'POST') {
2022-11-20 09:48:13 +01:00
const { ...data } = req.body;
if (!data.userId && !data.teamId) {
badRequest(res, 'A website must be assigned to a User or Team.');
}
try {
2022-11-20 09:48:13 +01:00
await updateWebsite(websiteId, data);
2022-11-19 03:49:58 +01:00
} catch (e: any) {
if (e.message.includes('Unique constraint') && e.message.includes('share_id')) {
return serverError(res, 'That share ID is already taken.');
}
}
return ok(res);
}
if (req.method === 'DELETE') {
2022-11-02 23:45:47 +01:00
await deleteWebsite(websiteId);
return ok(res);
}
return methodNotAllowed(res);
};