umami/queries/analytics/session/createSession.js

63 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-08-29 19:47:01 +02:00
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
2022-08-27 05:21:53 +02:00
import kafka from 'lib/kafka';
2022-08-29 19:47:01 +02:00
import prisma from 'lib/prisma';
2022-08-27 05:21:53 +02:00
import redis from 'lib/redis';
2022-07-12 23:14:36 +02:00
2022-07-22 23:43:19 +02:00
export async function createSession(...args) {
2022-08-28 06:38:35 +02:00
return runQuery({
[PRISMA]: () => relationalQuery(...args),
2022-07-25 18:47:11 +02:00
[CLICKHOUSE]: () => clickhouseQuery(...args),
}).then(async data => {
if (redis.enabled && data) {
await redis.set(`session:${data.id}`, data);
}
return data;
2022-07-22 23:43:19 +02:00
});
}
async function relationalQuery(websiteId, data) {
return prisma.client.session.create({
data: {
websiteId,
...data,
},
select: {
id: true,
hostname: true,
browser: true,
os: true,
screen: true,
language: true,
country: true,
device: true,
},
});
2022-07-12 23:14:36 +02:00
}
2022-07-22 23:43:19 +02:00
async function clickhouseQuery(
websiteId,
2022-11-01 07:42:37 +01:00
{ sessionId, hostname, browser, os, screen, language, country, device },
2022-07-22 23:43:19 +02:00
) {
2022-08-28 06:38:35 +02:00
const { getDateFormat, sendMessage } = kafka;
const website = await redis.get(`website:${websiteId}`);
2022-09-12 18:55:34 +02:00
const data = {
2022-11-01 07:42:37 +01:00
sessionId,
website_id: websiteId,
rev_id: website?.revId || 0,
2022-08-28 06:38:35 +02:00
created_at: getDateFormat(new Date()),
2022-09-12 18:55:34 +02:00
hostname,
browser,
os,
device,
screen,
language,
2022-08-01 09:28:38 +02:00
country: country ? country : null,
};
2022-07-22 23:43:19 +02:00
await sendMessage(data, 'event');
2022-08-27 05:21:53 +02:00
return data;
2022-07-22 23:43:19 +02:00
}