initial for v1
This commit is contained in:
committed by
Carl-Gerhard Lindesvärd
parent
c770634e73
commit
15e997129a
69
apps/api/src/routes/track.router.ts
Normal file
69
apps/api/src/routes/track.router.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { isBot } from '@/bots';
|
||||
import type { TrackHandlerPayload } from '@/controllers/track.controller';
|
||||
import { handler } from '@/controllers/track.controller';
|
||||
import { SdkAuthError, validateSdkRequest } from '@/utils/auth';
|
||||
import { logger } from '@/utils/logger';
|
||||
import type { FastifyPluginCallback, FastifyRequest } from 'fastify';
|
||||
|
||||
import { createBotEvent } from '@openpanel/db';
|
||||
|
||||
const eventRouter: FastifyPluginCallback = (fastify, opts, done) => {
|
||||
fastify.addHook(
|
||||
'preHandler',
|
||||
async (
|
||||
req: FastifyRequest<{
|
||||
Body: TrackHandlerPayload;
|
||||
}>,
|
||||
reply
|
||||
) => {
|
||||
try {
|
||||
const client = await validateSdkRequest(req.headers).catch((error) => {
|
||||
if (!(error instanceof SdkAuthError)) {
|
||||
logger.error(error, 'Failed to validate sdk request');
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
if (!client?.projectId) {
|
||||
return reply.status(401).send();
|
||||
}
|
||||
|
||||
req.projectId = client.projectId;
|
||||
req.client = client;
|
||||
|
||||
const bot = req.headers['user-agent']
|
||||
? isBot(req.headers['user-agent'])
|
||||
: null;
|
||||
|
||||
if (bot) {
|
||||
if (req.body.type === 'track') {
|
||||
const path = (req.body.payload.properties?.__path ||
|
||||
req.body.payload.properties?.path) as string | undefined;
|
||||
await createBotEvent({
|
||||
...bot,
|
||||
projectId: client.projectId,
|
||||
path: path ?? '',
|
||||
createdAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
reply.status(202).send('OK');
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error(e, 'Failed to create bot event');
|
||||
reply.status(401).send();
|
||||
return;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
fastify.route({
|
||||
method: 'POST',
|
||||
url: '/',
|
||||
handler: handler,
|
||||
});
|
||||
|
||||
done();
|
||||
};
|
||||
|
||||
export default eventRouter;
|
||||
Reference in New Issue
Block a user