Skip to content

Commit

Permalink
feat: ✨ queue zaraz method calls until initialized
Browse files Browse the repository at this point in the history
  • Loading branch information
HofmannZ committed Jan 17, 2024
1 parent c67e434 commit c797fcd
Showing 1 changed file with 44 additions and 8 deletions.
52 changes: 44 additions & 8 deletions src/helpers/get-zaraz.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,48 @@
/**
* A utility that checks if zaraz exists on the window object. If not it throws
* an error. Else returns the zaraz object.
*/
type QueueItem = {
method: 'track' | 'set' | 'ecommerce';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
arguments: any;
};

let queue: QueueItem[] = [];

export function getZaraz() {
if (typeof window !== 'undefined' && !window?.zaraz) {
throw new Error(
`Cannot use Zaraz Web API, because window.zaraz is not defined.`,
);
if (typeof window === 'undefined') {
throw new Error(`Cannot use Zaraz Web API, because window is not defined.`);
}

if (!window?.zaraz) {
// eslint-disable-next-line no-console
console.log(`Zaraz Web API is not initialized. Queueing events...`);

return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
track: (...args: any[]) => {
queue.push({ method: 'track', arguments: args });
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set: (...args: any[]) => {
queue.push({ method: 'set', arguments: args });
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ecommerce: (...args: any[]) => {
queue.push({ method: 'ecommerce', arguments: args });
},
};
}

if (queue.length > 0) {
// eslint-disable-next-line no-console
console.log(`Zaraz Web API is initialized. Flushing queue...`);

queue.forEach((event) => {
window.zaraz[event.method](...event.arguments);
});

// eslint-disable-next-line no-console
console.log(`Zaraz Web API queue flushed.`);

queue = []; // Clear the queue
}

return window.zaraz;
Expand Down

0 comments on commit c797fcd

Please sign in to comment.