Skip to content

Commit 736db66

Browse files
authored
Adding a traits injector plugin sample. (#126)
Adding a traits injector plugin sample.
1 parent dccfc5d commit 736db66

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.segment.analytics.next.plugins
2+
3+
import com.segment.analytics.kotlin.core.*
4+
import com.segment.analytics.kotlin.core.platform.Plugin
5+
import com.segment.analytics.kotlin.core.utilities.updateJsonObject
6+
import kotlinx.serialization.json.JsonObject
7+
8+
class InjectTraitsPlugin: Plugin {
9+
override val type: Plugin.Type = Plugin.Type.Enrichment
10+
override lateinit var analytics: Analytics
11+
12+
/*
13+
NOTE: This object acts as a cache for the traits object; We update it as we get
14+
identify events. Given its role as a cache, however, it should live as a global
15+
static object. Moving it to your Application class is a good solution.
16+
*/
17+
var cachedTraits: Traits = emptyJsonObject
18+
19+
override fun execute(event: BaseEvent): BaseEvent? {
20+
21+
if (event.type == EventType.Identify) {
22+
23+
// Grab trait related info from the identify event
24+
// and update the cache
25+
val jsonTraits= event.context.get("traits") as? JsonObject ?: emptyJsonObject
26+
27+
cachedTraits = updateJsonObject(cachedTraits) {
28+
it.putAll(jsonTraits)
29+
}
30+
} else {
31+
// All other events get the traits added to them.
32+
event.context = updateJsonObject(event.context) {
33+
it["traits"] = cachedTraits
34+
}
35+
}
36+
37+
return event
38+
}
39+
}

0 commit comments

Comments
 (0)