0.0.38 • Published 6 months ago

@radai/event-services-rad-client v0.0.38

Weekly downloads
-
License
-
Repository
-
Last release
6 months ago

event-services-rad-client

Client for sending events to Rad AI's Event Services

Quickstart

Assumes:

  • running in typescript
  • using React
  • using Vite

If any of these are not the case, you can still use the underlying packages @radai/event-services-gen-client and @radai/rad-service-client to compose your own client.

  1. Install the package from npm:
npm install @radai/event-services-rad-client
  1. Set the VITE_RADAI_INGEST_API_KEY environment variable to the access key for the Event Services API. See more about vite environment variables here.
VITE_RADAI_INGEST_API_KEY=XXX
  1. In your react-app, wrap your component with the "EventServicesProvider"
// Page.tsx
import { EventServicesProvider, EventServiceEnv } from '@radai/event-services-rad-client';

import Page from './Page';

// wrap the Page component in the EventServicesProvider.
// This makes the `useEventTracking` hooks available to all components in the app.
ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
).render(
  <React.StrictMode>
    <EventServicesProvider env={EventServiceEnv.LOCAL}>
      <Page />
    </EventServicesProvider>
  </React.StrictMode>
);
  1. Inside your component, you can use the useEventTracking hook to initalize the following functions: track, flush, setClientIds, reset.

Use setStaticAttributes to set attributes are the same across all events (must set "source") See the CloudStaticAttributes for more details.

Then, can use the track function to send events. Requries an event name and optional event metadata.

import { useEventTracking } from '@radai/event-services-rad-client';

export default function Page() {
  // note `useEventTracking` MUST be used inside of the EventServicesProvider
  const { track, flush, setStaticAttributes, reset } = useEventLifecycle();

  // set attributes that are the same across all events
  setStaticAttributes({ source: "QUICKSTART_DEMO" });

  return (
    <>
      <h1 className="text-4xl text-center my-4">Event Services Demo</h1>

      <div className="flex justify-center">
        <button
          className="px-4 py-2 bg-emerald-200 rounded-md"
          onClick={() => {
            track('testEvent', { userId: '123' });
          }}
        >
          Log Event
        </button>
      </div>
    </>
  );
}
  1. If you would like to add event tracking to a non-react function, you can use the track function directly. Note: must still be within the context of a EventServicesProvider.
import { track } from "@radai/event-services-rad-client";

export const HelloWorld = () => {
  track("HelloWorld");
};

API

We are using TSDoc to document the API. Below are the available functions and components. DO NOT EDIT MANUALLY. RUN npm run tsdoc to update the API documentation.

Functions

useEventLifecycle

Hook to access the functions to handle Event Lifecycle. Must be used in a component wrapped by the EventLifecycleProvider.

FunctionType
useEventLifecycle() => EventLifecycleContextType

EventLifecycleProvider

React provider to wrap an app or component that needs to track events.

FunctionType
EventLifecycleProviderReact.FC<{ apiClient: EventClient<void>; apiClientConfig?: ClientStaticAttributes or undefined; config?: EventLifecycleConfig or undefined; children?: any; }>

EventServicesProvider

React provider to handle the lifecycle of events as well as the client configuration.

This provider initializes the event services client and makes it available to all child components using the useEventLifecycle hook.

If you need to update the client configuration dynamically (e.g. token, headers, etc.), you can use the updateEventClientConfig function.

FunctionType
EventServicesProvider({ env, lifecycleConfig, children, }: EventServicesProviderProps) => any

Parameters:

  • env: - Event Service environment (local, dev, staging, prod)
  • lifecycleConfig: - Optional configuration for the event lifecycle (batching, retry, etc.)
  • children: - Optional children components

initializeEventManager

initialize the global EventManager with a trackFn, resetFn, and flushFn.

FunctionType
initializeEventManager(trackFn: TrackFn, resetFn: ResetFn, flushFn: FlushFn) => void

getEventManager

helper: get global instance of eventManager

FunctionType
getEventManager() => EventManager

track

track events inside of a EventManager context.

FunctionType
track(event: string, eventOptions?: JSONObject or undefined) => void

Parameters:

  • event: - The name of the event to track (this will be the "type" of Event)
  • eventOptions: - Optional additional fields to include in the event. Must be a JSON object.

reset

reset the EventManager context. Completely reset the tracking state.

FunctionType
reset() => void

flush

flush the EventManager context. Force the queue to immediately send all batched events.

FunctionType
flush() => void

resetManager

FunctionType
resetManager() => void

Constants

DEFAULT_CONFIG

ConstantType
DEFAULT_CONFIGRequired<EventLifecycleConfig>

EventLifecycleContext

ConstantType
EventLifecycleContextContext<EventLifecycleContextType or undefined>

CloudEventClient

wraps the generated EventsService client with CloudEvent specific config/validation.

Methods

setClientConfig

setClientConfig: function to configure generated client (e.x. accessToken: "MY_ACCESS_TOKEN" )

MethodType
setClientConfig(config: Config<boolean>) => void

Parameters:

  • config: - the client configuration.

e.x. client = new CloudEventClient(EventServiceEnv.DEV); client.setClientConfig({ accessToken: "MY_ACCESS_TOKEN" });

getClientConfig

helper function to get the generated client's configuration.

MethodType
getClientConfig() => Config<boolean>

setStaticAttributes

setStaticAttributes: initializes the CloudEvent configuration. Must include all required fields.

MethodType
setStaticAttributes(staticAttributes: CloudStaticAttributes) => void

Parameters:

  • staticAttributes: - static attributes for every event (e.g. source, userId, organization)

getStaticAttributes

getStaticAttributes: returns the static attributes for the client.

MethodType
getStaticAttributes() => CloudStaticAttributes

whenStaticAttributesSet

whenStaticAttributesSet: returns a promise that resolves when the static attributes are set.

MethodType
whenStaticAttributesSet() => Promise<CloudStaticAttributes>

send

Send events to the Event Service.

MethodType
send(events: JSONObject[]) => Promise<void>

Parameters:

  • events: - an array of JSON objects to send as events. Each object must have a "type" field.

EventManager

Singleton class to manage tracking events.

The class should get initalized one time. You can then use the track/reset/flush functions and know they will reference the same instance of the EventManager.

Methods

initTrackFn

Initializes tracking function for the EventManager.

MethodType
initTrackFn(trackFn: (event: string, eventOptions?: JSONObject or undefined) => void) => void

Parameters:

  • trackFn: - The function to track events.

initResetFn

MethodType
initResetFn(resetFn: () => void) => void

initFlushFn

MethodType
initFlushFn(flushFn: () => void) => void

track

Tracks an event using the provided event name and options.

MethodType
track(event: string, eventOptions?: JSONObject or undefined) => void

Parameters:

  • event: - The name of the event to track.
  • eventOptions: - Optional parameters for the event.

reset

MethodType
reset() => void

flush

MethodType
flush() => void

Properties

trackFn

PropertyType
trackFn((event: string, eventOptions?: JSONObject or undefined) => void) or undefined

resetFn

PropertyType
resetFn(() => void) or undefined

flushFn

PropertyType
flushFn(() => void) or undefined

Interfaces

EventLifecycleConfig

Configuration options for the EventLifecycleProvider.

PropertyTypeDescription
localStorageKeystring or undefinedDefault: RAD_SERVICE_CLIENT_KEY The key used to store data in local storage.
retryMaxAttemptsnumber or undefinedDefault: 3 The maximum number of retry attempts for failed events.
retryBackoffMsnumber or undefinedDefault: 1000 The backoff time in milliseconds between retry attempts.
batchSizenumber or undefinedDefault: 10 The number of events to process in a single batch.
flushIntervalnumber or undefinedDefault: 5000 The interval in milliseconds to flush the event queue.
queueMaxItemsnumber or undefinedDefault: 1000 The maximum number of items allowed in the event queue. Note if the max is reached, new events will NOT be added (dropped)

ClientStaticAttributes

PropertyTypeDescription

CloudStaticAttributes

Interface for the static attributes that are set on the client. These are the attributes that don't chnage between events. You can set these once and they will be included in every event you send.

See the required and optional fields below.

See the Event Service spec for more details: https://github.com/radaisystems/event-services/blob/main/components/event_services/models/cloudevent_schema.json

PropertyTypeDescription
sourcestringthe source of the event. Required at runtime. (this is the only required field to send an event)
specversionstring or undefinedthe CloudEvent spec version. Defaults to '1.0.2'.
datacontenttypestring or undefinedthe data content type. Defaults to 'application/json'.
userIdstring or undefinedthe unique user identifier to associate with the event. Useful for analytics.
deviceIdstring or undefinedthe unique device ID to associate with the event. Useful for analytics.
organizationstring or undefinedthe human readable organization to associate with the event. Useful for analytics.
sessionIdstring or undefineda UUID representing the unique session

EventLifecycleContextType

interface representing the functions available in the EventLifecycleContext

PropertyTypeDescription
track(event: string, eventOptions?: JSONObject or undefined) => voidTracks an event with optional event options. param: event - The name of the event to track.param: eventOptions - Optional JSON object containing additional event options.
setStaticAttributes(input: Partial<ClientStaticAttributes>) => voidSets the client IDs configuration. param: input - Partial configuration object for client IDs.
flush() => voidFlushes the event queue, sending all pending events.
reset() => voidResets the event lifecycle context to its initial state.

EventClient

Client to wrap the generated EventsService client.

PropertyTypeDescription
0.0.38

6 months ago

0.0.37

6 months ago

0.0.36

8 months ago

0.0.35

8 months ago

0.0.34

8 months ago

0.0.33

9 months ago

0.0.32

9 months ago

0.0.31

9 months ago

0.0.30

9 months ago

0.0.29

9 months ago

0.0.28

9 months ago

0.0.27

9 months ago

0.0.26

9 months ago

0.0.25

9 months ago

0.0.24

9 months ago

0.0.23

9 months ago

0.0.22

9 months ago

0.0.21

9 months ago

0.0.20

9 months ago

0.0.18

10 months ago

0.0.17

10 months ago

0.0.16

10 months ago

0.0.14

10 months ago

0.0.13

10 months ago

0.0.12

10 months ago

0.0.11

10 months ago

0.0.10

10 months ago

0.0.9

10 months ago

0.0.8

10 months ago

0.0.7

10 months ago

0.0.6

10 months ago

0.0.4

10 months ago

0.0.3

10 months ago

0.0.2

10 months ago

0.0.1

10 months ago

0.0.0

10 months ago