Skip to content

Instantly share code, notes, and snippets.

@ayyash
Created April 18, 2022 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayyash/131248dcf4d7bc06a4022b0975687335 to your computer and use it in GitHub Desktop.
Save ayyash/131248dcf4d7bc06a4022b0975687335 to your computer and use it in GitHub Desktop.
// GTM service
declare let dataLayer: any[]; // Declare google tagexport enum EnumGtmSource {
// any source in web is added here
// left side is internal, right side is GTM
ProductsList = 'products list',
ProductsRelatedList = 'products related',
ProjectsList = 'projects list',
// ...etc
}
export enum EnumGtmEvent {
// any event are added here, prefixed with garage to clear head
// left side is internal, right side is GTM
Login = 'garage_login',
PageView = 'garage_page_view',
// ...etc
}
export interface IGtmTrack {
event: EnumGtmEvent;
source?: EnumGtmSource;
}
export class GtmTracking {
public static RegisterEvent(track: IGtmTrack, extra?: any): void {
const data = { event: track.event }; // depending on event, map, something like this
data['of some attribute'] = GtmTracking.MapExtra(extra); // push data
dataLayer.push(data);
} // the mappers that take an existing model, and turn it into GTM model
// for example products:
private static MapProducts(products: IProduct[]) {
// map products to "items"
return { items: products.map(GtmTracking.MapProduct) };
}
private static MapProduct(product: IProduct, index: number) {
// limitation on GTM, the property names must be identified by GA4 for easiest operations
return {
item_name: product.name,
item_id: product.id,
price: product.price,
currency: 'AUD',
index
};
}
// then all other mappers for employee, and project, search, login... etc
private static MapSearch(keyword: string) {
return { search_term: keyword };
}
private static MapLogin(method: string) {
// this better turn into Enum to tame it
return { method };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment