Skip to content

Adding a traits injector plugin sample. #126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.segment.analytics.next.plugins

import com.segment.analytics.kotlin.core.*
import com.segment.analytics.kotlin.core.platform.Plugin
import com.segment.analytics.kotlin.core.utilities.updateJsonObject
import kotlinx.serialization.json.JsonObject

class InjectTraitsPlugin: Plugin {
override val type: Plugin.Type = Plugin.Type.Enrichment
override lateinit var analytics: Analytics

/*
NOTE: This object acts as a cache for the traits object; We update it as we get
identify events. Given its role as a cache, however, it should live as a global
static object. Moving it to your Application class is a good solution.
*/
var cachedTraits: Traits = emptyJsonObject

override fun execute(event: BaseEvent): BaseEvent? {

if (event.type == EventType.Identify) {

// Grab trait related info from the identify event
// and update the cache
val jsonTraits= event.context.get("traits") as? JsonObject ?: emptyJsonObject

cachedTraits = updateJsonObject(cachedTraits) {
it.putAll(jsonTraits)
}
} else {
// All other events get the traits added to them.
event.context = updateJsonObject(event.context) {
it["traits"] = cachedTraits
}
}

return event
}
}