Handle website delete. Added response helper functions.

This commit is contained in:
Mike Cao 2020-08-07 17:19:42 -07:00
parent 0a411a9ad6
commit c4b75e4aec
31 changed files with 314 additions and 96 deletions

View file

@ -1,12 +1,31 @@
import { getWebsite } from 'lib/db';
import { deleteWebsite, getWebsite } from 'lib/db';
import { useAuth } from 'lib/middleware';
import { methodNotAllowed, ok, unauthorized } from 'lib/response';
export default async (req, res) => {
await useAuth(req, res);
const { user_id, is_admin } = req.auth;
const { id } = req.query;
const website_id = +id;
const website = await getWebsite({ website_id: +id });
if (req.method === 'GET') {
const website = await getWebsite({ website_id });
return res.status(200).json(website);
return ok(res, website);
}
if (req.method === 'DELETE') {
const website = await getWebsite({ website_id });
if (website.user_id === user_id || is_admin) {
await deleteWebsite(website_id);
return ok(res);
}
return unauthorized(res);
}
return methodNotAllowed(res);
};

View file

@ -1,5 +1,6 @@
import { getMetrics } from 'lib/db';
import { useAuth } from 'lib/middleware';
import { ok } from 'lib/response';
export default async (req, res) => {
await useAuth(req, res);
@ -17,5 +18,5 @@ export default async (req, res) => {
return obj;
}, {});
return res.status(200).json(stats);
return ok(res, stats);
};

View file

@ -1,6 +1,7 @@
import moment from 'moment-timezone';
import { getPageviewData } from 'lib/db';
import { useAuth } from 'lib/middleware';
import { ok, badRequest } from 'lib/response';
const unitTypes = ['month', 'hour', 'day'];
@ -10,7 +11,7 @@ export default async (req, res) => {
const { id, start_at, end_at, unit, tz } = req.query;
if (!moment.tz.zone(tz) || !unitTypes.includes(unit)) {
return res.status(400).end();
return badRequest(res);
}
const start = new Date(+start_at);
@ -21,5 +22,5 @@ export default async (req, res) => {
getPageviewData(+id, start, end, tz, unit, 'distinct session_id'),
]);
return res.status(200).json({ pageviews, uniques });
return ok(res, { pageviews, uniques });
};

View file

@ -1,5 +1,6 @@
import { getRankings } from 'lib/db';
import { useAuth } from 'lib/middleware';
import { ok, badRequest } from 'lib/response';
const sessionColumns = ['browser', 'os', 'device', 'country'];
const pageviewColumns = ['url', 'referrer'];
@ -10,12 +11,12 @@ export default async (req, res) => {
const { id, type, start_at, end_at } = req.query;
if (!sessionColumns.includes(type) && !pageviewColumns.includes(type)) {
return res.status(400).end();
return badRequest(res);
}
const table = sessionColumns.includes(type) ? 'session' : 'pageview';
const rankings = await getRankings(+id, new Date(+start_at), new Date(+end_at), type, table);
return res.status(200).json(rankings);
return ok(res, rankings);
};