umami/pages/api/realtime.js

73 lines
1.8 KiB
JavaScript
Raw Normal View History

2020-10-09 08:26:05 +02:00
import { subMinutes } from 'date-fns';
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';
export default async (req, res) => {
await useAuth(req, res);
2020-10-09 08:26:05 +02:00
async function getData(websites, time) {
const [pageviews, sessions, events] = await Promise.all([
2020-10-09 08:26:05 +02:00
getPageviews(websites, time),
getSessions(websites, time),
getEvents(websites, time),
]);
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(),
};
}
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 });
const data = await getData(ids, subMinutes(new Date(), 30));
2020-10-09 08:26:05 +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);
const data = await getData(websites, new Date(+start_at));
2020-10-09 08:26:05 +02:00
return ok(res, data);
2020-10-09 08:26:05 +02:00
}
2020-10-09 08:26:05 +02:00
return badRequest(res);
}
return methodNotAllowed(res);
};