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

76 lines
1.8 KiB
JavaScript
Raw Normal View History

import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { getRandomChars, methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
2022-10-12 22:11:44 +02:00
import { deleteWebsite, getAccount, getWebsite, updateWebsite } from 'queries';
import { TYPE_WEBSITE } from 'lib/constants';
export default async (req, res) => {
2022-10-12 22:11:44 +02:00
await useCors(req, res);
await useAuth(req, res);
const { id: websiteUuid } = req.query;
2022-10-12 22:11:44 +02:00
if (req.method === 'GET') {
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
const website = await getWebsite({ websiteUuid });
return ok(res, website);
}
if (req.method === 'POST') {
if (!(await allowQuery(req, TYPE_WEBSITE, false))) {
return unauthorized(res);
}
2022-10-12 22:11:44 +02:00
const { name, domain, owner, enableShareUrl, shareId } = req.body;
const { accountUuid } = req.auth;
2022-10-30 00:50:29 +02:00
2022-10-08 02:13:03 +02:00
let account;
if (accountUuid) {
account = await getAccount({ accountUuid });
if (!account) {
return serverError(res, 'Account does not exist.');
}
}
const website = await getWebsite({ websiteUuid });
2022-10-12 22:11:44 +02:00
const newShareId = enableShareUrl ? website.shareId || getRandomChars(8) : null;
try {
await updateWebsite(
{
name,
domain,
shareId: shareId ? shareId : newShareId,
2022-10-31 18:38:37 +01:00
userId: +owner || account.id,
},
{ websiteUuid },
);
} catch (e) {
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') {
if (!(await allowQuery(req, TYPE_WEBSITE, false))) {
return unauthorized(res);
}
await deleteWebsite(websiteUuid);
return ok(res);
}
return methodNotAllowed(res);
};