trackEvent function in Motia codebase.

Ramu NarasingaRamu Narasinga
1 min read

In this article, we review trackEvent function in Motia codebase. We will look at:

  1. trackEvent function.

  2. Usage

Press enter or click to view image in full size

trackEvent function

You will find the following code in analytics/utils.ts

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const trackEvent = (eventName: string, properties: Record<string, any> = {}) => {
  try {
    if (isAnalyticsEnabled()) {
      track(eventName, properties, {
        user_id: getUserIdentifier() || 'unknown',
      })
    }
  } catch (error) {
    // Silently fail to not disrupt dev server
  }
}

track is imported at the top of this file as shown below:

import { track } from '@amplitude/analytics-node'

getUserIdentifier()

getUserIdentifier() is defined as shown below:

export const getUserIdentifier = (): string => {
  const userInfo = `${os.userInfo().username}${os.hostname()}`
  return crypto.createHash('sha256').update(userInfo).digest('hex').substring(0, 16)
}

Usage

Below is an example picked from call-step-file.ts

trackEvent('step_execution_started', {
      stepName: step.config.name,
      language: command,
      type: step.config.type,
      streams: streams.length,
})

It is recommended to name your events using snake_case in Amplitude, like in this one, ‘step_execution_started’.

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Want to learn from open-source? Solve challenges inspired by open-source projects.

References:

  1. https://github.com/MotiaDev/motia/blob/main/packages/snap/src/dev.ts#L41

  2. https://github.com/MotiaDev/motia/blob/main/packages/core/src/analytics/utils.ts#L35

0
Subscribe to my newsletter

Read articles from Ramu Narasinga directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ramu Narasinga
Ramu Narasinga

I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.