@radai/event-services-rad-client v0.0.38
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.
- Install the package from npm:
npm install @radai/event-services-rad-client- Set the
VITE_RADAI_INGEST_API_KEYenvironment variable to the access key for the Event Services API. See more about vite environment variables here.
VITE_RADAI_INGEST_API_KEY=XXX- 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>
);- 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>
</>
);
}- 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
- EventLifecycleProvider
- EventServicesProvider
- initializeEventManager
- getEventManager
- track
- reset
- flush
- resetManager
useEventLifecycle
Hook to access the functions to handle Event Lifecycle. Must be used in a component wrapped by the EventLifecycleProvider.
| Function | Type |
|---|---|
useEventLifecycle | () => EventLifecycleContextType |
EventLifecycleProvider
React provider to wrap an app or component that needs to track events.
| Function | Type |
|---|---|
EventLifecycleProvider | React.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.
| Function | Type |
|---|---|
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.
| Function | Type |
|---|---|
initializeEventManager | (trackFn: TrackFn, resetFn: ResetFn, flushFn: FlushFn) => void |
getEventManager
helper: get global instance of eventManager
| Function | Type |
|---|---|
getEventManager | () => EventManager |
track
track events inside of a EventManager context.
| Function | Type |
|---|---|
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.
| Function | Type |
|---|---|
reset | () => void |
flush
flush the EventManager context. Force the queue to immediately send all batched events.
| Function | Type |
|---|---|
flush | () => void |
resetManager
| Function | Type |
|---|---|
resetManager | () => void |
Constants
DEFAULT_CONFIG
| Constant | Type |
|---|---|
DEFAULT_CONFIG | Required<EventLifecycleConfig> |
EventLifecycleContext
| Constant | Type |
|---|---|
EventLifecycleContext | Context<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" )
| Method | Type |
|---|---|
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.
| Method | Type |
|---|---|
getClientConfig | () => Config<boolean> |
setStaticAttributes
setStaticAttributes: initializes the CloudEvent configuration. Must include all required fields.
| Method | Type |
|---|---|
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.
| Method | Type |
|---|---|
getStaticAttributes | () => CloudStaticAttributes |
whenStaticAttributesSet
whenStaticAttributesSet: returns a promise that resolves when the static attributes are set.
| Method | Type |
|---|---|
whenStaticAttributesSet | () => Promise<CloudStaticAttributes> |
send
Send events to the Event Service.
| Method | Type |
|---|---|
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.
| Method | Type |
|---|---|
initTrackFn | (trackFn: (event: string, eventOptions?: JSONObject or undefined) => void) => void |
Parameters:
trackFn: - The function to track events.
initResetFn
| Method | Type |
|---|---|
initResetFn | (resetFn: () => void) => void |
initFlushFn
| Method | Type |
|---|---|
initFlushFn | (flushFn: () => void) => void |
track
Tracks an event using the provided event name and options.
| Method | Type |
|---|---|
track | (event: string, eventOptions?: JSONObject or undefined) => void |
Parameters:
event: - The name of the event to track.eventOptions: - Optional parameters for the event.
reset
| Method | Type |
|---|---|
reset | () => void |
flush
| Method | Type |
|---|---|
flush | () => void |
Properties
trackFn
| Property | Type |
|---|---|
trackFn | ((event: string, eventOptions?: JSONObject or undefined) => void) or undefined |
resetFn
| Property | Type |
|---|---|
resetFn | (() => void) or undefined |
flushFn
| Property | Type |
|---|---|
flushFn | (() => void) or undefined |
Interfaces
EventLifecycleConfig
Configuration options for the EventLifecycleProvider.
| Property | Type | Description |
|---|---|---|
localStorageKey | string or undefined | Default: RAD_SERVICE_CLIENT_KEY The key used to store data in local storage. |
retryMaxAttempts | number or undefined | Default: 3 The maximum number of retry attempts for failed events. |
retryBackoffMs | number or undefined | Default: 1000 The backoff time in milliseconds between retry attempts. |
batchSize | number or undefined | Default: 10 The number of events to process in a single batch. |
flushInterval | number or undefined | Default: 5000 The interval in milliseconds to flush the event queue. |
queueMaxItems | number or undefined | Default: 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
| Property | Type | Description |
|---|
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
| Property | Type | Description |
|---|---|---|
source | string | the source of the event. Required at runtime. (this is the only required field to send an event) |
specversion | string or undefined | the CloudEvent spec version. Defaults to '1.0.2'. |
datacontenttype | string or undefined | the data content type. Defaults to 'application/json'. |
userId | string or undefined | the unique user identifier to associate with the event. Useful for analytics. |
deviceId | string or undefined | the unique device ID to associate with the event. Useful for analytics. |
organization | string or undefined | the human readable organization to associate with the event. Useful for analytics. |
sessionId | string or undefined | a UUID representing the unique session |
EventLifecycleContextType
interface representing the functions available in the EventLifecycleContext
| Property | Type | Description |
|---|---|---|
track | (event: string, eventOptions?: JSONObject or undefined) => void | Tracks 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>) => void | Sets the client IDs configuration. param: input - Partial configuration object for client IDs. |
flush | () => void | Flushes the event queue, sending all pending events. |
reset | () => void | Resets the event lifecycle context to its initial state. |
EventClient
Client to wrap the generated EventsService client.
| Property | Type | Description |
|---|
6 months ago
6 months ago
8 months ago
8 months ago
8 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago