Introduction
With the Analytics client implemented, we want to use the Events as trigger to the requests. This means that, for every event listened, we want to perform a request to the Analytics app. So, for every X seconds, we will have a new data on Live Products.
Events
In VTEX IO, events are often used as triggers to other actions, such as sending e-mails to the final client. To implement this, we need to configure our app's client and event handler.
Using an event as trigger to perform a request
-
As the Analytics client is implemented, we just need to use it in the event handler. First, in the
node/event/liveUsersUpdate.tsfile, import the client we implemented in the previous step:_10import { Clients } from '../clients/index' -
Now, we need to use the
EventContextthat we already configured before. Import it by updating the method. You can do so like this:_10//node/event/liveUsersUpdate.ts_10import { Clients } from './../clients/index'_10+import { EventContext } from '@vtex/api'_10_10+export async function updateLiveUsers(ctx: EventContext<Clients>) {_10..._10}Note: you can also globally declare your event context in the
index.tsfile. If you do so, you don't need to import in every file you want to use it. -
Now, to use the Analytics client, do the following:
_10//node/event/liveUsersUpdate.ts_10export async function updateLiveUsers(ctx: EventContext<Clients>) {_10+ const liveUsersProducts = await ctx.clients.analytics.getLiveUsers()_10+ console.log('LIVE USERS: ', liveUsersProducts)_10+ return true_10} -
Finally, run
vtex link, and for every event fired, you should see the live users retrieved from the Analytics.The result should be like this:
