Files
stats/apps/api/src/hooks/is-bot.hook.ts
Carl-Gerhard Lindesvärd 4483e464d1 fix: optimize event buffer (#278)
* fix: how we fetch profiles in the buffer

* perf: optimize event buffer

* remove unused file

* fix

* wip

* wip: try groupmq 2

* try simplified event buffer with duration calculation on the fly instead
2026-03-16 13:29:40 +01:00

49 lines
1.3 KiB
TypeScript

import { createBotEvent } from '@openpanel/db';
import type {
DeprecatedPostEventPayload,
ITrackHandlerPayload,
} from '@openpanel/validation';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { isBot } from '@/bots';
export async function isBotHook(
req: FastifyRequest<{
Body: ITrackHandlerPayload | DeprecatedPostEventPayload;
}>,
reply: FastifyReply
) {
const bot = req.headers['user-agent']
? await isBot(req.headers['user-agent'])
: null;
if (bot && req.client?.projectId) {
if ('type' in req.body && req.body.type === 'track') {
const path = (req.body.payload.properties?.__path ||
req.body.payload.properties?.path) as string | undefined;
if (path) {
await createBotEvent({
...bot,
projectId: req.client.projectId,
path: path ?? '',
createdAt: new Date(),
});
}
// Handle deprecated events (v1)
} else if ('name' in req.body && 'properties' in req.body) {
const path = (req.body.properties?.__path || req.body.properties?.path) as
| string
| undefined;
if (path) {
await createBotEvent({
...bot,
projectId: req.client.projectId,
path: path ?? '',
createdAt: new Date(),
});
}
}
return reply.status(202).send({ bot });
}
}