Using events as triggers
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.
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.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 don'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:
Any questions?
See the answersheet for this step or check our [office hours] on the VTEX Developers channel(https://www.youtube.com/c/VTEXDevelopers)
Help us make this content better!
VTEX IO courses are open source. If you see something wrong, you can open a pull request!
Make a contributionUpdated 11 months ago