# All files / src/_utils genericAnalyticsClient.ts

36.36% Statements 8/22
0% Branches 0/5
33.33% Functions 1/3
38.88% Lines 7/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    661x
    1x

    1x
    1x

    1x

    1x

    1x
     import { mergeDeepRight } from 'ramda'
    import { detectPrng, factory } from 'ulid'

    const prng = detectPrng(true) // pass `true` to allow insecure Math.rand
    const ulid = factory(prng)

    interface RequestInfo extends RequestInit {
      headers: Record<string, any>
    }

    interface AnalyticsConfig {
      bodyParams?: Record<string, any>
      client: (endpoint: string, request: RequestInfo) => void
      endpoint: string
      headers?: Object
    }

    export interface IAnalytics {
      bodyParams: Record<string, any>
      client: (endpoint: string, request: RequestInfo) => void
      endpoint: string
      headers: Object

      trackEvent: (event: string, properties: Record<string, any>) => void
    }

    export class Analytics implements IAnalytics {
      bodyParams: Record<string, any>
      client: (endpoint: string, request: RequestInfo) => void
      endpoint: string
      headers: Object

      constructor({
        bodyParams = {},
        client,
        endpoint,
        headers = {},
      }: AnalyticsConfig) {
        this.endpoint = endpoint
        this.headers = headers
        this.bodyParams = bodyParams
        this.client = client
        this.trackEvent = this.trackEvent.bind(this)
      }

      trackEvent(event: string, Iproperties: Record<string, any> = {}) {
        const time = new Date()
        return this.client(this.endpoint, {
          method: 'POST',
          headers: this.headers,
          body: JSON.stringify(
            mergeDeepRight(
              {
                key: event,
                properties,
                timestamp: time,
                event_id: ulid(),
                page_id: ulid(),
              },
              this.bodyParams
            )
          ),
        })
      }
    }