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

69 lines
1.7 KiB
TypeScript
Raw Normal View History

import { NextApiResponse } from 'next';
import { methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
import { Website, NextApiRequestQueryBody } from 'lib/types';
import { canViewWebsite, canUpdateWebsite, canDeleteWebsite } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
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;
}
export default async (
2022-11-18 07:46:05 +01:00
req: NextApiRequestQueryBody<WebsiteRequestQuery, WebsiteRequestBody>,
2022-11-23 00:06:52 +01:00
res: NextApiResponse<Website>,
2022-11-15 22:21:14 +01:00
) => {
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-10-12 22:11:44 +02:00
if (req.method === 'GET') {
if (!(await canViewWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2022-11-02 23:45:47 +01:00
const website = await getWebsite({ id: websiteId });
return ok(res, website);
}
if (req.method === 'POST') {
if (!(await canUpdateWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
const { name, domain, shareId } = req.body;
let website;
try {
website = await updateWebsite(websiteId, { name, domain, shareId });
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, website);
}
if (req.method === 'DELETE') {
if (!(await canDeleteWebsite(req.auth, websiteId))) {
return unauthorized(res);
}
2022-11-02 23:45:47 +01:00
await deleteWebsite(websiteId);
return ok(res);
}
return methodNotAllowed(res);
};