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

53 lines
1.2 KiB
JavaScript
Raw Normal View History

import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
2022-11-02 23:45:47 +01:00
import { methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
import { deleteWebsite, 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);
2022-11-02 23:45:47 +01:00
const { id: websiteId } = req.query;
if (!(await allowQuery(req, TYPE_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-02 23:45:47 +01:00
const { name, domain, shareId } = req.body;
try {
2022-11-02 23:45:47 +01:00
await updateWebsite(websiteId, {
name,
domain,
shareId,
});
} 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))) {
return unauthorized(res);
}
2022-11-02 23:45:47 +01:00
await deleteWebsite(websiteId);
return ok(res);
}
return methodNotAllowed(res);
};