forked from PostHog/posthog-avo-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
148 lines (134 loc) · 4.55 KB
/
index.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { randomUUID } from 'crypto'
import { Plugin } from '@posthog/plugin-scaffold'
import fetch from 'node-fetch'
interface AvoInspectorMeta {
global: {
defaultHeaders: Record<string, string>
}
config: {
appName: string
avoApiKey: string
environment: string
}
}
type AvoInspectorPlugin = Plugin<AvoInspectorMeta>
export const setupPlugin: AvoInspectorPlugin['setupPlugin'] = async ({ config, global }) => {
global.defaultHeaders = {
env: config.environment,
'api-key': config.avoApiKey,
'content-type': 'application/json',
accept: 'application/json',
}
}
export const exportEvents: AvoInspectorPlugin['exportEvents'] = async (events, { config, global }) => {
if (events.length === 0) {
return
}
const sessionId = randomUUID()
const now = new Date().toISOString()
const avoEvents = []
const baseEventPayload = {
apiKey: config.avoApiKey,
env: config.environment,
appName: config.appName,
sessionId: sessionId,
createdAt: now,
avoFunction: false,
eventId: null,
eventHash: null,
appVersion: '1.0.0',
libVersion: '1.0.0',
libPlatform: 'node',
messageId: '5875bc8b-a8e6-4f20-a499-8af557467a02',
trackingId: '',
samplingRate: 1,
type: 'event',
eventName: 'event_name',
eventProperties: [],
}
for (const event of events) {
avoEvents.push({
...baseEventPayload,
eventName: event.event,
messageId: event.uuid,
eventProperties: event.properties ? convertPosthogPropsToAvoProps(event.properties) : [],
})
}
try {
// start a tracking session
const sessionStartRes = await fetch('https://api.avo.app/inspector/posthog/v1/track', {
method: 'POST',
headers: global.defaultHeaders,
body: JSON.stringify([
{
apiKey: config.avoApiKey,
env: config.environment,
appName: config.appName,
createdAt: now,
sessionId: sessionId,
appVersion: '1.0.0',
libVersion: '1.0.1',
libPlatform: 'node',
messageId: randomUUID(),
trackingId: '',
samplingRate: 1,
type: 'sessionStarted',
},
]),
})
if (sessionStartRes.status !== 200) {
throw new Error(`sessionStarted request failed with status code ${sessionStartRes.status}`)
}
// track events
const trackEventsRes = await fetch('https://api.avo.app/inspector/posthog/v1/track', {
method: 'POST',
headers: global.defaultHeaders,
body: JSON.stringify(avoEvents),
})
// https://github.com/node-fetch/node-fetch/issues/1262
const trackEventsResJson = (await trackEventsRes.json()) as Record<string, any> | null
if (
trackEventsRes.status !== 200 ||
!trackEventsResJson ||
('ok' in trackEventsResJson && !trackEventsResJson.ok)
) {
throw new Error('track events request failed')
}
console.log(`Succesfully sent ${events.length} events to Avo`)
} catch (err) {
const errorMessage = err instanceof Error ? err.message : String(err)
console.error('Unable to send data to Avo with error:', errorMessage)
}
}
const convertPosthogPropsToAvoProps = (properties: Record<string, any>): Record<string, string>[] => {
const avoProps = []
for (const [propertyName, propertyValue] of Object.entries(properties)) {
avoProps.push({ propertyName, propertyType: getPropValueType(propertyValue) })
}
return avoProps
}
// Compatible with the Avo Rudderstack integration
const getPropValueType = (propValue: any): string => {
let propType = typeof propValue
if (propValue == null) {
return 'null'
} else if (propType === 'string') {
return 'string'
} else if (propType === 'number' || propType === 'bigint') {
if ((propValue + '').indexOf('.') >= 0) {
return 'float'
} else {
return 'int'
}
} else if (propType === 'boolean') {
return 'boolean'
} else if (propType === 'object') {
if (Array.isArray(propValue)) {
return 'list'
} else {
return 'object'
}
} else {
return propType
}
}