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

  1. 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'
    
  2. 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.

  3. 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
    }
    
  4. 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:
    imageimage

Any questions?

See the answersheet for this step or join us on our office hours


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 contribution

or open an issue