Skip to content

Commit

Permalink
event name check
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderkirtzel committed Dec 19, 2024
1 parent e6a2e23 commit fadcad9
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions packages/sources/datalayer/src/push.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import type { WalkerOS } from '@elbwalker/types';
import type { Config } from './types';
import { clone, filterValues, isArguments, tryCatch } from '@elbwalker/utils';
import {
clone,
filterValues,
isArguments,
isArray,
isObject,
tryCatch,
} from '@elbwalker/utils';
import { objToEvent, gtagToObj } from './mapping';

export function intercept(config: Config) {
Expand All @@ -20,24 +27,20 @@ export function push(config: Config, ...args: unknown[]) {
(...args: unknown[]) => {
// Clone the arguments to avoid mutation
const clonedArgs = clone(args);
const entries = getEntries(clonedArgs);

// Get the pushed items
const items = isArguments(clonedArgs[0])
? [gtagToObj(clonedArgs[0])] // Convert gtag to dataLayer
: clonedArgs; // Regular dataLayer push

items.forEach((obj) => {
entries.forEach((obj) => {
// Map the incoming event to a WalkerOS event
const mappedObj = objToEvent(filterValues(obj), config);

if (mappedObj) {
const { command, event } = mappedObj;

if (command) {
config.elb(command.name, command.data as WalkerOS.PushData);
if (command.name)
config.elb(command.name, command.data as WalkerOS.PushData);
} else if (event) {
// Hand over to walker instance
config.elb(event);
if (event.event) config.elb(event);
}
}
});
Expand All @@ -46,3 +49,9 @@ export function push(config: Config, ...args: unknown[]) {
console.error,
)(...args);
}

function getEntries(args: unknown[]): unknown[] {
if (isArray(args) && isArguments(args[0])) return [gtagToObj(args[0])]; // gtag
if (isObject(args)) return [args]; // dataLayer.push
return args;
}

0 comments on commit fadcad9

Please sign in to comment.