2020-10-09 08:26:05 +02:00
|
|
|
import { subMinutes } from 'date-fns';
|
2020-10-09 00:02:48 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2020-10-09 08:26:05 +02:00
|
|
|
import { ok, methodNotAllowed, badRequest } from 'lib/response';
|
|
|
|
import { getEvents, getPageviews, getSessions, getUserWebsites } from 'lib/queries';
|
|
|
|
import { createToken, parseToken } from 'lib/crypto';
|
2020-10-09 00:02:48 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
2020-10-09 08:26:05 +02:00
|
|
|
async function getData(websites, time) {
|
2020-10-09 19:48:47 +02:00
|
|
|
const [pageviews, sessions, events] = await Promise.all([
|
2020-10-09 08:26:05 +02:00
|
|
|
getPageviews(websites, time),
|
|
|
|
getSessions(websites, time),
|
|
|
|
getEvents(websites, time),
|
|
|
|
]);
|
2020-10-09 19:48:47 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
pageviews: pageviews.map(({ view_id, ...props }) => ({
|
|
|
|
__id: `p${view_id}`,
|
|
|
|
view_id,
|
|
|
|
...props,
|
|
|
|
})),
|
|
|
|
sessions: sessions.map(({ session_id, ...props }) => ({
|
|
|
|
__id: `s${session_id}`,
|
|
|
|
session_id,
|
|
|
|
...props,
|
|
|
|
})),
|
|
|
|
events: events.map(({ event_id, ...props }) => ({
|
|
|
|
__id: `e${event_id}`,
|
|
|
|
event_id,
|
|
|
|
...props,
|
|
|
|
})),
|
|
|
|
timestamp: Date.now(),
|
|
|
|
};
|
2020-10-09 00:02:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2020-10-09 10:04:06 +02:00
|
|
|
const { type, start_at } = req.query;
|
2020-10-09 08:26:05 +02:00
|
|
|
const { user_id } = req.auth;
|
|
|
|
|
|
|
|
if (type === 'init') {
|
|
|
|
const websites = await getUserWebsites(user_id);
|
|
|
|
const ids = websites.map(({ website_id }) => website_id);
|
|
|
|
const token = await createToken({ websites: ids });
|
2020-10-09 19:48:47 +02:00
|
|
|
const data = await getData(ids, subMinutes(new Date(), 30));
|
2020-10-09 08:26:05 +02:00
|
|
|
|
2020-10-09 19:48:47 +02:00
|
|
|
return ok(res, {
|
|
|
|
websites,
|
|
|
|
token,
|
|
|
|
data,
|
|
|
|
});
|
2020-10-09 08:26:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if (type === 'update') {
|
|
|
|
const token = req.headers['x-umami-token'];
|
|
|
|
|
|
|
|
if (!token) {
|
|
|
|
return badRequest(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
const { websites } = await parseToken(token);
|
|
|
|
|
2020-10-09 19:48:47 +02:00
|
|
|
const data = await getData(websites, new Date(+start_at));
|
2020-10-09 08:26:05 +02:00
|
|
|
|
2020-10-09 19:48:47 +02:00
|
|
|
return ok(res, data);
|
2020-10-09 08:26:05 +02:00
|
|
|
}
|
2020-10-09 00:02:48 +02:00
|
|
|
|
2020-10-09 08:26:05 +02:00
|
|
|
return badRequest(res);
|
2020-10-09 00:02:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|