umami/pages/api/realtime/init.ts
2022-12-08 23:43:43 -08:00

30 lines
905 B
TypeScript

import { subMinutes } from 'date-fns';
import { RealtimeInit } from 'lib/types';
import { NextApiRequestAuth } from 'lib/types';
import { secret } from 'lib/crypto';
import { useAuth } from 'lib/middleware';
import { NextApiResponse } from 'next';
import { createToken, methodNotAllowed, ok } from 'next-basics';
import { getRealtimeData, getUserWebsites } from 'queries';
export default async (req: NextApiRequestAuth, res: NextApiResponse<RealtimeInit>) => {
await useAuth(req, res);
if (req.method === 'GET') {
const { id: userId } = req.auth.user;
const websites = await getUserWebsites(userId);
const ids = websites.map(({ id }) => id);
const token = createToken({ websites: ids }, secret());
const data = await getRealtimeData(ids, subMinutes(new Date(), 30));
return ok(res, {
websites,
token,
data,
});
}
return methodNotAllowed(res);
};