diff options
| author | Fuwn <[email protected]> | 2026-01-24 13:09:50 +0000 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2026-01-24 13:09:50 +0000 |
| commit | 396acf3bbbe00a192cb0ea0a9ccf91b1d8d2850b (patch) | |
| tree | b9df4ca6a70db45cfffbae6fdd7252e20fb8e93c /src/queries/sql/getActiveVisitors.ts | |
| download | umami-396acf3bbbe00a192cb0ea0a9ccf91b1d8d2850b.tar.xz umami-396acf3bbbe00a192cb0ea0a9ccf91b1d8d2850b.zip | |
Created from https://vercel.com/new
Diffstat (limited to 'src/queries/sql/getActiveVisitors.ts')
| -rw-r--r-- | src/queries/sql/getActiveVisitors.ts | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/src/queries/sql/getActiveVisitors.ts b/src/queries/sql/getActiveVisitors.ts new file mode 100644 index 0000000..d763c12 --- /dev/null +++ b/src/queries/sql/getActiveVisitors.ts @@ -0,0 +1,50 @@ +import { subMinutes } from 'date-fns'; +import clickhouse from '@/lib/clickhouse'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import prisma from '@/lib/prisma'; + +const FUNCTION_NAME = 'getActiveVisitors'; + +export async function getActiveVisitors(...args: [websiteId: string]) { + return runQuery({ + [PRISMA]: () => relationalQuery(...args), + [CLICKHOUSE]: () => clickhouseQuery(...args), + }); +} + +async function relationalQuery(websiteId: string) { + const { rawQuery } = prisma; + const startDate = subMinutes(new Date(), 5); + + const result = await rawQuery( + ` + select count(distinct session_id) as "visitors" + from website_event + where website_id = {{websiteId::uuid}} + and created_at >= {{startDate}} + `, + { websiteId, startDate }, + FUNCTION_NAME, + ); + + return result?.[0] ?? null; +} + +async function clickhouseQuery(websiteId: string): Promise<{ x: number }> { + const { rawQuery } = clickhouse; + const startDate = subMinutes(new Date(), 5); + + const result = await rawQuery( + ` + select + count(distinct session_id) as "visitors" + from website_event + where website_id = {websiteId:UUID} + and created_at >= {startDate:DateTime64} + `, + { websiteId, startDate }, + FUNCTION_NAME, + ); + + return result[0] ?? null; +} |