Documentation
Feedback
Guides
Learning Center

Learning Center
Learning Center
Using events as triggers
View in Portuguese
This content was migrated from the VTEX Learning Center and is no longer being actively maintained. For the most accurate and up-to-date information, please check the official documentation.

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:


    _10
    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:


    _10
    //node/event/liveUsersUpdate.ts
    _10
    import { 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.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:


    _10
    //node/event/liveUsersUpdate.ts
    _10
    export async function updateLiveUsers(ctx: EventContext<Clients>) {
    _10
    + const liveUsersProducts = await ctx.clients.analytics.getLiveUsers()
    _10
    + console.log('LIVE USERS: ', liveUsersProducts)
    _10
    + return true
    _10
    }

  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:

    {"base64":"  ","img":{"width":1306,"height":506,"type":"png","mime":"image/png","wUnits":"px","hUnits":"px","length":102072,"url":"https://user-images.githubusercontent.com/43679629/85150833-69ffda80-b229-11ea-9260-b9255adf7d9c.png"}}


Answer sheet

See answer sheet for liveUsersUpdate.ts
liveUsersUpdate.ts

_10
// node/event/liveUsersUpdate.ts
_10
import { Clients } from '../clients/index'
_10
import { EventContext } from '@vtex/api'
_10
_10
export async function updateLiveUsers(ctx: EventContext<Clients>) {
_10
const liveUsersProducts = await ctx.clients.analytics.getLiveUsers()
_10
console.log('LIVE USERS: ', liveUsersProducts)
_10
return true
_10
}

On this page