2020-10-10 20:04:07 +02:00
|
|
|
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';
|
2020-10-10 20:04:07 +02:00
|
|
|
|
2022-11-15 22:21:14 +01:00
|
|
|
export default async (req: NextApiRequestAuth, res: NextApiResponse<RealtimeInit>) => {
|
2020-10-10 20:04:07 +02:00
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2022-11-09 16:40:17 +01:00
|
|
|
const { id: userId } = req.auth.user;
|
2020-10-10 20:04:07 +02:00
|
|
|
|
2022-11-18 18:47:06 +01:00
|
|
|
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());
|
2020-10-10 20:04:07 +02:00
|
|
|
const data = await getRealtimeData(ids, subMinutes(new Date(), 30));
|
|
|
|
|
|
|
|
return ok(res, {
|
|
|
|
websites,
|
|
|
|
token,
|
|
|
|
data,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return methodNotAllowed(res);
|
|
|
|
};
|