forked from Openpanel-dev/openpanel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent.controller.ts
More file actions
59 lines (54 loc) · 1.68 KB
/
Copy pathevent.controller.ts
File metadata and controls
59 lines (54 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { generateId } from '@openpanel/common';
import { parseUserAgent } from '@openpanel/common/server';
import { getSalts } from '@openpanel/db';
import { getGeoLocation } from '@openpanel/geo';
import { getEventsGroupQueueShard } from '@openpanel/queue';
import type { DeprecatedPostEventPayload } from '@openpanel/validation';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { getStringHeaders, getTimestamp } from './track.controller';
import { getDeviceId } from '@/utils/ids';
export async function postEvent(
request: FastifyRequest<{
Body: DeprecatedPostEventPayload;
}>,
reply: FastifyReply
) {
const { timestamp } = getTimestamp(request.timestamp, request.body);
const ip = request.clientIp;
const ua = request.headers['user-agent'] ?? 'unknown/1.0';
const projectId = request.client?.projectId;
const headers = getStringHeaders(request.headers);
if (!projectId) {
reply.status(400).send('missing origin');
return;
}
const [salts, geo] = await Promise.all([getSalts(), getGeoLocation(ip)]);
const { deviceId, sessionId } = await getDeviceId({
projectId,
ip,
ua,
salts,
eventMs: new Date(timestamp).getTime(),
});
const uaInfo = parseUserAgent(ua, request.body?.properties);
const groupId = uaInfo.isServer
? `${projectId}:${request.body?.profileId ?? generateId()}`
: deviceId;
await getEventsGroupQueueShard(groupId).add({
orderMs: new Date(timestamp).getTime(),
data: {
projectId,
headers,
event: {
...request.body,
timestamp,
},
uaInfo,
geo,
deviceId,
sessionId: sessionId ?? '',
},
groupId,
});
reply.status(202).send('ok');
}