umami/queries/analytics/event/saveEvent.js
2022-09-12 09:55:34 -07:00

53 lines
1.3 KiB
JavaScript

import { EVENT_NAME_LENGTH, URL_LENGTH } from 'lib/constants';
import { CLICKHOUSE, PRISMA, runQuery } from 'lib/db';
import kafka from 'lib/kafka';
import prisma from 'lib/prisma';
export async function saveEvent(...args) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(website_id, { session_id, url, event_name, event_data }) {
const data = {
website_id,
session_id,
url: url?.substring(0, URL_LENGTH),
event_name: event_name?.substring(0, EVENT_NAME_LENGTH),
};
if (event_data) {
data.event_data = {
create: {
event_data: event_data,
},
};
}
return prisma.client.event.create({
data,
});
}
async function clickhouseQuery(
website_id,
{ session: { country, ...sessionArgs }, event_uuid, url, event_name, event_data },
) {
const { getDateFormat, sendMessage } = kafka;
const params = {
event_uuid,
website_id,
created_at: getDateFormat(new Date()),
url: url?.substring(0, URL_LENGTH),
event_name: event_name?.substring(0, EVENT_NAME_LENGTH),
event_data: JSON.stringify(event_data),
...sessionArgs,
country: country ? country : null,
};
await sendMessage(params, 'event');
}