-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
event-tracking: Cache events captured while offline in a IndexedDB th…
…at persists between sessions This way, if the user uses the application while offline and close it, without ever being online in that session, we still preserve the events and send them when possible in a following online usage.
- Loading branch information
1 parent
19f8986
commit 0b3ba49
Showing
1 changed file
with
82 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,105 @@ | ||
import ky from 'ky' | ||
import localforage from 'localforage' | ||
import posthog from 'posthog-js' | ||
|
||
type EventPayload = { | ||
/** | ||
* The name of the event | ||
*/ | ||
eventName: string | ||
/** | ||
* The moment the event was captured (in milliseconds since epoch) | ||
*/ | ||
timestamp: number | ||
/** | ||
* Arbitrary properties to be recorded with the event | ||
*/ | ||
properties?: Record<string, unknown> | ||
} | ||
|
||
/** | ||
* PostHog client | ||
* | ||
*/ | ||
class PostHog { | ||
class EventTracker { | ||
static postHogApiUrl = 'https://us.i.posthog.com' | ||
static postHogApiKey = 'phc_SfqVeZcpYHmhUn9NRizThxFxiI9fKqvjRjmBDB8ToRs' | ||
static posthog: ReturnType<typeof posthog.init> | undefined = undefined | ||
eventTrackingQueue: LocalForage | ||
|
||
/** | ||
* Initialize the PostHog client if not already initialized | ||
* Initialize the event tracking system | ||
*/ | ||
constructor() { | ||
if (!PostHog.posthog) { | ||
PostHog.posthog = posthog.init('phc_SfqVeZcpYHmhUn9NRizThxFxiI9fKqvjRjmBDB8ToRs', { | ||
api_host: 'https://us.i.posthog.com', | ||
if (!EventTracker.posthog) { | ||
EventTracker.posthog = posthog.init(EventTracker.postHogApiKey, { | ||
api_host: EventTracker.postHogApiUrl, | ||
person_profiles: 'always', // Create profiles for anonymous users as well | ||
}) | ||
} | ||
|
||
if (!this.eventTrackingQueue) { | ||
this.eventTrackingQueue = localforage.createInstance({ | ||
driver: localforage.INDEXEDDB, | ||
name: 'Cockpit - Event-tracking Queue', | ||
storeName: 'cockpit-event-tracking-queue', | ||
version: 1.0, | ||
description: 'Queue of events to be sent to the event tracking system.', | ||
}) | ||
} | ||
|
||
this.sendEvents() | ||
} | ||
|
||
/** | ||
* Capture an event | ||
* @param {string} eventName - The name of the event | ||
* @param {Record<string, unknown>} properties - The properties of the event | ||
* @param {Record<string, unknown>} eventProperties - The properties of the event | ||
*/ | ||
async capture(eventName: string, eventProperties?: Record<string, unknown>): Promise<void> { | ||
const eventId = `${eventName}-${Date.now()}` | ||
const eventPayload: EventPayload = { | ||
eventName, | ||
timestamp: Date.now(), | ||
properties: eventProperties, | ||
} | ||
await this.eventTrackingQueue.setItem(eventId, eventPayload) | ||
await this.sendEvents() | ||
} | ||
|
||
/** | ||
* Send all events in the queue to the event tracking system | ||
*/ | ||
capture(eventName: string, properties?: Record<string, unknown>): void { | ||
if (!PostHog.posthog) { | ||
throw new Error('PostHog client not initialized.') | ||
async sendEvents(): Promise<void> { | ||
const queuedEventsKeys = await this.eventTrackingQueue.keys() | ||
const successfullySentEventsKeys: string[] = [] | ||
|
||
for (const eventId of queuedEventsKeys) { | ||
const eventPayload = await this.eventTrackingQueue.getItem<EventPayload>(eventId) | ||
if (!eventPayload) continue | ||
|
||
try { | ||
const body = { | ||
api_key: EventTracker.postHogApiKey, | ||
event: eventPayload.eventName, | ||
properties: eventPayload.properties, | ||
timestamp: eventPayload.timestamp, | ||
distinct_id: EventTracker.posthog?.get_distinct_id(), | ||
} | ||
|
||
await ky.post(`${EventTracker.postHogApiUrl}/capture/`, { json: body, mode: 'no-cors', throwHttpErrors: false }) | ||
successfullySentEventsKeys.push(eventId) | ||
console.log('Event sent successfully:', eventId) | ||
} catch (error) { | ||
console.error('Error sending event to PostHog:', error) | ||
break | ||
} | ||
} | ||
|
||
for (const eventId of successfullySentEventsKeys) { | ||
await this.eventTrackingQueue.removeItem(eventId) | ||
} | ||
PostHog.posthog.capture(eventName, properties) | ||
} | ||
} | ||
|
||
const eventTracker = new PostHog() | ||
const eventTracker = new EventTracker() | ||
export default eventTracker |