This repository has been archived by the owner on Aug 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
58 lines (54 loc) · 2.13 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
import Reader, { CityResponse, Response } from 'mmdb-lib'
import { PluginMeta, PluginEvent, PluginAttachment } from '@posthog/plugin-scaffold'
interface Meta extends PluginMeta {
config: {
localhostIP: string
}
attachments: {
maxmindMmdb?: PluginAttachment
}
global: {
ipLookup?: Reader<Response>
}
}
export async function setupPlugin({ attachments, global }: Meta) {
if (attachments.maxmindMmdb) {
global.ipLookup = new Reader(attachments.maxmindMmdb.contents)
}
}
export function processEvent(event: PluginEvent, { global, config }: Meta) {
if (event.ip === '127.0.0.1' && config.localhostIP) {
event.ip = config.localhostIP
}
if (event.ip && event.properties && global.ipLookup) {
const response = global.ipLookup.get(event.ip) as CityResponse
if (response) {
if (response.city) {
event.properties['$city_name'] = response.city.names?.en
}
if (response.country) {
event.properties['$country_name'] = response.country.names?.en
event.properties['$country_code'] = response.country.iso_code
}
if (response.continent) {
event.properties['$continent_name'] = response.continent.names?.en
event.properties['$continent_code'] = response.continent.code
}
if (response.postal) {
event.properties['$postal_code'] = response.postal.code
}
if (response.location) {
event.properties['$latitude'] = response.location?.latitude
event.properties['$longitude'] = response.location?.longitude
event.properties['$time_zone'] = response.location?.time_zone
}
if (response.subdivisions) {
response.subdivisions.forEach((subDivision, index) => {
event.properties[`$subdivision_${index + 1}_code`] = subDivision.iso_code
event.properties[`$subdivision_${index + 1}_name`] = subDivision.names?.en
})
}
}
}
return event
}