umami/pages/api/realtime/init.ts

30 lines
905 B
TypeScript
Raw Normal View History

import { subMinutes } from 'date-fns';
2022-12-07 03:36:41 +01:00
import { RealtimeInit } from 'lib/types';
import { NextApiRequestAuth } from 'lib/types';
2022-08-29 05:20:54 +02:00
import { secret } from 'lib/crypto';
2022-11-15 22:21:14 +01:00
import { useAuth } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { createToken, methodNotAllowed, ok } from 'next-basics';
import { getRealtimeData, getUserWebsites } from 'queries';
2022-11-15 22:21:14 +01:00
export default async (req: NextApiRequestAuth, res: NextApiResponse<RealtimeInit>) => {
await useAuth(req, res);
if (req.method === 'GET') {
2022-11-09 16:40:17 +01:00
const { id: userId } = req.auth.user;
const websites = await getUserWebsites(userId);
2022-11-01 07:42:37 +01:00
const ids = websites.map(({ id }) => id);
2022-08-29 05:20:54 +02:00
const token = createToken({ websites: ids }, secret());
const data = await getRealtimeData(ids, subMinutes(new Date(), 30));
return ok(res, {
websites,
token,
data,
});
}
return methodNotAllowed(res);
};