umami/queries/analytics/pageview/savePageView.ts

105 lines
2.3 KiB
TypeScript
Raw Normal View History

import { URL_LENGTH, EVENT_TYPE } from 'lib/constants';
2022-08-29 19:47:01 +02:00
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import kafka from 'lib/kafka';
import prisma from 'lib/prisma';
import cache from 'lib/cache';
import { uuid } from 'lib/crypto';
2022-07-16 01:47:38 +02:00
export async function savePageView(args: {
id: string;
websiteId: string;
url: string;
referrer?: string;
2023-03-01 19:53:57 +01:00
pageTitle?: string;
hostname?: string;
browser?: string;
os?: string;
device?: string;
screen?: string;
language?: string;
country?: string;
subdivision1?: string;
subdivision2?: string;
city?: string;
}) {
2022-08-28 06:38:35 +02:00
return runQuery({
[PRISMA]: () => relationalQuery(args),
[CLICKHOUSE]: () => clickhouseQuery(args),
2022-07-22 23:43:19 +02:00
});
}
2022-07-12 23:14:36 +02:00
async function relationalQuery(data: {
id: string;
websiteId: string;
url: string;
referrer?: string;
2023-03-01 19:53:57 +01:00
pageTitle?: string;
}) {
2023-03-01 19:53:57 +01:00
const { websiteId, id: sessionId, url, referrer, pageTitle } = data;
return prisma.client.websiteEvent.create({
2022-08-28 06:38:35 +02:00
data: {
id: uuid(),
websiteId,
sessionId,
2022-08-28 06:38:35 +02:00
url: url?.substring(0, URL_LENGTH),
referrer: referrer?.substring(0, URL_LENGTH),
2023-03-01 19:53:57 +01:00
pageTitle: pageTitle,
eventType: EVENT_TYPE.pageView,
2022-08-28 06:38:35 +02:00
},
});
2022-07-12 23:14:36 +02:00
}
2022-07-22 23:43:19 +02:00
async function clickhouseQuery(data: {
id: string;
websiteId: string;
url: string;
referrer?: string;
pageTitle?: string;
hostname?: string;
browser?: string;
os?: string;
device?: string;
screen?: string;
language?: string;
country?: string;
subdivision1?: string;
subdivision2?: string;
city?: string;
}) {
const {
websiteId,
id: sessionId,
url,
referrer,
2023-03-01 19:53:57 +01:00
pageTitle,
country,
subdivision1,
subdivision2,
city,
...args
} = data;
2022-08-28 06:38:35 +02:00
const { getDateFormat, sendMessage } = kafka;
const website = await cache.fetchWebsite(websiteId);
const message = {
website_id: websiteId,
session_id: sessionId,
rev_id: website?.revId || 0,
2022-11-09 02:47:19 +01:00
country: country ? country : null,
subdivision1: subdivision1 ? subdivision1 : null,
subdivision2: subdivision2 ? subdivision2 : null,
city: city ? city : null,
url: url?.substring(0, URL_LENGTH),
referrer: referrer?.substring(0, URL_LENGTH),
2023-03-01 19:53:57 +01:00
page_title: pageTitle,
event_type: EVENT_TYPE.pageView,
created_at: getDateFormat(new Date()),
2022-11-09 02:47:19 +01:00
...args,
2022-08-05 02:43:47 +02:00
};
await sendMessage(message, 'event');
return data;
2022-08-05 02:43:47 +02:00
}