feat: separate mongoQuery & add mongo filter

This commit is contained in:
minkik 2023-05-19 14:10:53 +09:00 committed by Joseph Lee
parent 4c57ab1388
commit b5b689b156
15 changed files with 858 additions and 710 deletions

View file

@ -1,72 +1,31 @@
import { subMinutes } from 'date-fns';
import prisma from 'lib/prisma';
import clickhouse from 'lib/clickhouse';
import { runQuery, CLICKHOUSE, PRISMA } from 'lib/db';
import { runQuery, CLICKHOUSE, PRISMA, MONGODB } from 'lib/db';
export async function getActiveVisitors(...args: [websiteId: string]) {
return runQuery({
[PRISMA]: () => relationalQuery(...args),
[MONGODB]: () => mongodbQuery(...args),
[CLICKHOUSE]: () => clickhouseQuery(...args),
});
}
async function relationalQuery(websiteId: string) {
const { getDatabaseType, toUuid, rawQuery, client } = prisma;
const db = getDatabaseType();
const { toUuid, rawQuery } = prisma;
const date = subMinutes(new Date(), 5);
const params: any = [websiteId, date];
if (db === 'mongodb') {
const result: any = await client.websiteEvent.aggregateRaw({
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: ['$website_id', websiteId],
},
{
$gte: [
'$created_at',
{
$dateFromString: {
dateString: date.toISOString(),
},
},
],
},
],
},
},
},
{
$group: {
_id: '$session_id',
},
},
{
$count: 'x',
},
],
});
if (result.length > 0) {
return { x: result[0].x };
} else {
return { x: 0 };
}
} else {
return rawQuery(
`select count(distinct session_id) x
return rawQuery(
`select count(distinct session_id) x
from website_event
join website
on website_event.website_id = website.website_id
where website.website_id = $1${toUuid()}
and website_event.created_at >= $2`,
params,
);
}
params,
);
}
async function clickhouseQuery(websiteId: string) {
@ -81,3 +40,48 @@ async function clickhouseQuery(websiteId: string) {
params,
);
}
async function mongodbQuery(websiteId: string) {
const { client } = prisma;
const date = subMinutes(new Date(), 5);
const result: any = await client.websiteEvent.aggregateRaw({
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: ['$website_id', websiteId],
},
{
$gte: [
'$created_at',
{
$dateFromString: {
dateString: date.toISOString(),
},
},
],
},
],
},
},
},
{
$group: {
_id: '$session_id',
},
},
{
$count: 'x',
},
],
});
if (result.length > 0) {
return { x: result[0].x };
} else {
return { x: 0 };
}
}