2020-10-10 20:04:07 +02:00
|
|
|
import { subMinutes } from 'date-fns';
|
2023-01-19 00:09:49 +01:00
|
|
|
import { ok, unauthorized, methodNotAllowed, createToken } from 'next-basics';
|
2020-10-10 20:04:07 +02:00
|
|
|
import { useAuth } from 'lib/middleware';
|
2022-07-12 23:14:36 +02:00
|
|
|
import { getUserWebsites, getRealtimeData } from 'queries';
|
2022-08-29 05:20:54 +02:00
|
|
|
import { secret } from 'lib/crypto';
|
2020-10-10 20:04:07 +02:00
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
await useAuth(req, res);
|
|
|
|
|
|
|
|
if (req.method === 'GET') {
|
2022-10-10 22:42:18 +02:00
|
|
|
const { userId } = req.auth;
|
2020-10-10 20:04:07 +02:00
|
|
|
|
2023-01-19 00:09:49 +01:00
|
|
|
if (!userId) {
|
|
|
|
return unauthorized(res);
|
|
|
|
}
|
|
|
|
|
2022-10-26 00:48:49 +02:00
|
|
|
const websites = await getUserWebsites({ userId });
|
2022-10-12 08:09:06 +02:00
|
|
|
const ids = websites.map(({ websiteUuid }) => websiteUuid);
|
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);
|
|
|
|
};
|