package com.amplitude.pluginengagementreactnative import com.amplitude.core.events.BaseEvent import com.facebook.react.bridge.ReadableMap /** * Reads an optional numeric field off a JS payload. * * [ReadableMap]'s primitive getters return unboxed values, so they throw `NoSuchKeyException` * when the key is absent or null — unlike `getString`/`getMap`, which are nullable and simply * return null. Every primitive read therefore has to be guarded. */ private fun ReadableMap.getLongOrNull(key: String): Long? = if (hasKey(key) && !isNull(key)) getDouble(key).toLong() else null /** * Maps a JS event payload onto the [BaseEvent] the engagement SDK consumes. * * Returns null when the payload has no `event_type`, the one field we can't forward without. * Everything else is optional: events reaching the plugin have not been through the analytics * pipeline yet, so `event_id` in particular is routinely absent. */ internal fun readableMapToBaseEvent(event: ReadableMap): BaseEvent? { val baseEvent = BaseEvent() baseEvent.eventType = event.getString("event_type") ?: return null baseEvent.eventId = event.getLongOrNull("event_id") baseEvent.platform = event.getString("platform") baseEvent.osName = event.getString("os_name") baseEvent.osVersion = event.getString("os_version") baseEvent.eventProperties = event.getMap("event_properties")?.toHashMap()?.toMutableMap() baseEvent.groupProperties = event.getMap("group_properties")?.toHashMap()?.toMutableMap() baseEvent.groups = event.getMap("groups")?.toHashMap()?.toMutableMap() baseEvent.userProperties = event.getMap("user_properties")?.toHashMap()?.toMutableMap() return baseEvent }