Skip to content

Commit

Permalink
feat: add tracker context
Browse files Browse the repository at this point in the history
  • Loading branch information
emkis committed Apr 3, 2022
1 parent 066c841 commit 22735ef
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/tracker-context/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { createTrackerContext } from './tracker-context'
export type { TrackerContext } from './tracker-context-types'
24 changes: 24 additions & 0 deletions src/tracker-context/tracker-context-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { EventProperties } from '../data-layer'

/**
* Tracker context scope.
* @public
*/
export type TrackerContext = Readonly<{
/**
* An object containing the context properties.
* @internal
*/
context: { readonly value: EventProperties }

/**
* Sets context properties.
*
* It could be used to set or update properties in this context.
* @public
* @example
* const context = createTrackerContext({ userId: 'not defined' })
* context.setProps({ userId: '2f9kfo7', foo: 'bar' })
*/
setProps: (props: EventProperties) => void
}>
29 changes: 29 additions & 0 deletions src/tracker-context/tracker-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { EventProperties } from '../data-layer'
import type { TrackerContext } from './tracker-context-types'

/**
* Creates a context for track events.
*
* All properties in this context will be injected into every
* track event that uses this context.
*
* @param initialProps - Properties witch will initialize the context.
* @public
* @example
* createTrackerContext({
* appVersion: '1.2.7',
* userId: getUserIdFromSomewhere()
* // Properties you need to send in all track events
* })
*/
export function createTrackerContext(
initialProps: EventProperties = {}
): TrackerContext {
const context = { value: { ...initialProps } }

function setProps(props: EventProperties) {
context.value = { ...props }
}

return { context, setProps }
}

0 comments on commit 22735ef

Please sign in to comment.