From ecf54bc49ba816ed43698898ac3db369caadbbf3 Mon Sep 17 00:00:00 2001 From: asmirnov Date: Fri, 9 Jun 2023 16:43:43 +0400 Subject: [PATCH] just the case on which you can see the issue with async operations inside handler --- src/index.ts | 29 ++++++++++++++++++++++++----- src/track.ts | 19 ++++++++++++++----- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index 7e7e742..9cf6409 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,24 +3,43 @@ import { track } from './track' import { getOrderPayload, getPageviewPayload } from './payload' export default function (manager: Manager, settings: ComponentSettings) { - manager.addEventListener('pageview', event => { - return track(event, getPageviewPayload(event, settings)) + manager.addEventListener('pageview', async event => { + console.log('Event pageview: ' + JSON.stringify(event)) + + const res = await track(event, getPageviewPayload(event, settings)) + + console.log(`--> and here is another log we wont see`, 123) + + console.log( + `--> this track() wont be invoked, at least i didnt see the log inside the fn second time` + ) + const res2 = await track(event, getPageviewPayload(event, settings)) + + console.log(`--> no log for res2`, res2) + + return res }) - manager.addEventListener('ecommerce', event => { + manager.addEventListener('ecommerce', async event => { + console.log('Event ecommerce: ' + JSON.stringify(event)) const action = event.name || event.payload.name || event.payload.ecommerce.name switch (action) { case 'Product Viewed': { - return track(event, getPageviewPayload(event, settings)) + const res = await track(event, getPageviewPayload(event, settings)) + console.log('res', res) + return res } case 'Order Completed': { - return track(event, getOrderPayload(event, settings)) + const res = await track(event, getOrderPayload(event, settings)) + console.log('res', res) + return res } default: { + console.log('Wrong action', action) return } } diff --git a/src/track.ts b/src/track.ts index 936a150..6db1e23 100644 --- a/src/track.ts +++ b/src/track.ts @@ -2,15 +2,24 @@ import { MCEvent } from '@managed-components/types' import { DemaPayload } from './types' export const track = async (event: MCEvent, payload: DemaPayload) => { + console.log('Run track', event, payload) + const url = new URL('https://tracker.dema.ai/track.js') for (const [key, value] of Object.entries(payload)) { url.searchParams.set(key, value) } - return fetch(url.toString(), { - headers: { - 'User-Agent': event.client.userAgent, - }, - }) + // console.log('Track: ' + url.toString()) + + // let's use API that works 100% just for testing + console.log('Track:', 'jsonplaceholder') + + // return fetch(url.toString(), { + return fetch('https://jsonplaceholder.typicode.com/posts') + .then(response => response.json()) + .then(response => { + console.log('--> Here is the response we wont see', response) + return response + }) }