umami/pages/api/realtime.js

50 lines
1.4 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) {
return Promise.all([
getPageviews(websites, time),
getSessions(websites, time),
getEvents(websites, time),
]);
}
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 [pageviews, sessions, events] = await getData(ids, subMinutes(new Date(), 30));
const token = await createToken({ websites: ids });
return ok(res, { websites, token, data: { pageviews, sessions, events } });
}
if (type === 'update') {
const token = req.headers['x-umami-token'];
if (!token) {
return badRequest(res);
}
const { websites } = await parseToken(token);
2020-10-09 10:04:06 +02:00
const [pageviews, sessions, events] = await getData(websites, new Date(+start_at));
2020-10-09 08:26:05 +02:00
return ok(res, { pageviews, sessions, events });
}
2020-10-09 08:26:05 +02:00
return badRequest(res);
}
return methodNotAllowed(res);
};