Events: Using Events as Triggers
github-learning-lab opened this issue · comments
Events: Using Events as Triggers
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.
Activity
-
As the Analytics client is implemented, we just need to use it in the event handler. First, in the
node/event/liveUsersUpdate.ts
file, import the client we implemented in the previous step:import { Clients } from '../clients/index'
-
Now, we need to use the
EventContext
that we already configured before. Import it by updating the method. You can do so like this://node/event/liveUsersUpdate.ts import { Clients } from './../clients/index' +import { EventContext } from '@vtex/api' +export async function updateLiveUsers(ctx: EventContext<Clients>) { ... }
Note: you can also globally declare your event context in the
index.ts
file. If you do so, you doesn't need to import in every file you want to use it. -
Now, to use the Analytics client, do the following:
//node/event/liveUsersUpdate.ts export async function updateLiveUsers(ctx: EventContext<Clients>) { + const liveUsersProducts = await ctx.clients.analytics.getLiveUsers() + console.log('LIVE USERS: ', liveUsersProducts) + return true }
-
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: