-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.ts
62 lines (58 loc) · 2.48 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
import { Plugin } from '@posthog/plugin-scaffold'
const plugin: Plugin = {
processEvent: async (event, { geoip }) => {
if (!geoip) {
throw new Error('This PostHog version does not have GeoIP capabilities! Upgrade to PostHog 1.24.0 or later')
}
if (event.ip) {
if (event.ip === '127.0.0.1') {
event.ip = '13.106.122.3' // Spoofing an Australian IP address for local development
}
const response = await geoip.locate(event.ip)
if (response) {
const location: Record<string, any> = {}
if (response.city) {
location['city_name'] = response.city.names?.en
}
if (response.country) {
location['country_name'] = response.country.names?.en
location['country_code'] = response.country.isoCode
}
if (response.continent) {
location['continent_name'] = response.continent.names?.en
location['continent_code'] = response.continent.code
}
if (response.postal) {
location['postal_code'] = response.postal.code
}
if (response.location) {
location['latitude'] = response.location?.latitude
location['longitude'] = response.location?.longitude
location['time_zone'] = response.location?.timeZone
}
if (response.subdivisions) {
for (const [index, subdivision] of response.subdivisions.entries()) {
location[`subdivision_${index + 1}_code`] = subdivision.isoCode
location[`subdivision_${index + 1}_name`] = subdivision.names?.en
}
}
if (!event.properties) {
event.properties = {}
}
if (!event.$set) {
event.$set = {}
}
if (!event.$set_once) {
event.$set_once = {}
}
for (const [key, value] of Object.entries(location)) {
event.properties[`$geoip_${key}`] = value
event.$set[`$geoip_${key}`] = value
event.$set_once[`$initial_geoip_${key}`] = value
}
}
}
return event
},
}
module.exports = plugin