sdk: track duration and set global events

This commit is contained in:
Carl-Gerhard Lindesvärd
2023-11-01 20:35:23 +01:00
parent 3f7db1935c
commit 5a4765526b

View File

@@ -108,6 +108,9 @@ class Batcher<T extends any> {
} }
send() { send() {
if(this.timer) {
clearTimeout(this.timer)
}
this.callback(this.queue) this.callback(this.queue)
this.queue = [] this.queue = []
} }
@@ -119,6 +122,8 @@ export class Mixan {
private profileId?: string private profileId?: string
private options: MixanOptions private options: MixanOptions
private logger: (...args: any[]) => void private logger: (...args: any[]) => void
private globalProperties: Record<string, any> = {}
private lastScreenViewAt?: string
constructor(options: MixanOptions) { constructor(options: MixanOptions) {
this.logger = options.verbose ? console.log : () => {} this.logger = options.verbose ? console.log : () => {}
@@ -130,7 +135,7 @@ export class Mixan {
'/events', '/events',
queue.map((item) => ({ queue.map((item) => ({
...item, ...item,
profileId: item.profileId || this.profileId || null, profileId: item.profileId || this.profileId || null,
})) }))
) )
}) })
@@ -144,7 +149,10 @@ export class Mixan {
this.logger('Mixan: Queue event', name) this.logger('Mixan: Queue event', name)
this.eventBatcher.add({ this.eventBatcher.add({
name, name,
properties, properties: {
...this.globalProperties,
...properties,
},
time: this.timestamp(), time: this.timestamp(),
profileId: this.profileId || null, profileId: this.profileId || null,
}) })
@@ -188,6 +196,11 @@ export class Mixan {
}) })
} }
async setGlobalProperties(properties: Record<string, any>) {
this.logger('Mixan: Set global properties', properties);
this.globalProperties = properties ?? {}
}
async increment(name: string, value: number = 1) { async increment(name: string, value: number = 1) {
if (!this.profileId) { if (!this.profileId) {
this.logger('Mixan: Increment failed, no profileId'); this.logger('Mixan: Increment failed, no profileId');
@@ -218,13 +231,30 @@ export class Mixan {
}) })
} }
async screenView(route: string, properties?: Record<string, any>) { async screenView(route: string, _properties?: Record<string, any>) {
const properties = _properties ?? {}
const now = new Date()
if(this.lastScreenViewAt) {
const last = new Date(this.lastScreenViewAt)
const diff = now.getTime() - last.getTime()
this.logger(`Mixan: Screen view duration: ${diff}ms`)
properties['duration'] = diff
}
this.lastScreenViewAt = now.toISOString()
await this.event('screen_view', { await this.event('screen_view', {
...(properties || {}), ...properties,
route, route,
}) })
} }
flush() {
this.logger('Mixan: Flushing events queue')
this.eventBatcher.send()
this.lastScreenViewAt = undefined
}
clear() { clear() {
this.logger('Mixan: Clear, send remaining events and remove profileId'); this.logger('Mixan: Clear, send remaining events and remove profileId');
this.eventBatcher.send() this.eventBatcher.send()