Update website fetch and update.

This commit is contained in:
Mike Cao 2022-11-02 15:45:47 -07:00
parent 05245ca316
commit 1075325ec5
5 changed files with 27 additions and 59 deletions

View file

@ -1,52 +1,34 @@
import { allowQuery } from 'lib/auth';
import { useAuth, useCors } from 'lib/middleware';
import { getRandomChars, methodNotAllowed, ok, serverError, unauthorized } from 'next-basics';
import { deleteWebsite, getUser, getWebsite, updateWebsite } from 'queries';
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) => {
await useCors(req, res);
await useAuth(req, res);
const { id } = req.query;
const { id: websiteId } = req.query;
if (!(await allowQuery(req, TYPE_WEBSITE))) {
return unauthorized(res);
}
if (req.method === 'GET') {
const website = await getWebsite({ id });
const website = await getWebsite({ id: websiteId });
return ok(res, website);
}
if (req.method === 'POST') {
const { name, domain, owner, enableShareUrl, shareId } = req.body;
const { userId } = req.auth;
let user;
if (userId) {
user = await getUser({ id: userId });
if (!user) {
return serverError(res, 'User does not exist.');
}
}
const website = await getWebsite({ id });
const newShareId = enableShareUrl ? website.shareId || getRandomChars(8) : null;
const { name, domain, shareId } = req.body;
try {
await updateWebsite(
{
name,
domain,
shareId: shareId ? shareId : newShareId,
userId: +owner || user.id,
},
{ id },
);
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.');
@ -61,7 +43,7 @@ export default async (req, res) => {
return unauthorized(res);
}
await deleteWebsite(id);
await deleteWebsite(websiteId);
return ok(res);
}