Skip to content

Commit

Permalink
Minor code shuffle to optimize further
Browse files Browse the repository at this point in the history
  • Loading branch information
saikumarrs committed Sep 6, 2021
1 parent 18ba1b1 commit 2cdf911
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 118 deletions.
215 changes: 99 additions & 116 deletions analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -300,71 +300,62 @@ class Analytics {
// object.clientIntegrationObjects.length
// );

let readyIntgCount = 0;
object.clientIntegrationObjects.forEach((intg) => {
// logger.debug("===looping over each successful integration====")
if (!intg.isReady || intg.isReady()) {
readyIntgCount += 1;
// logger.debug("===letting know I am ready=====", intg.name)
}
});

if (readyIntgCount == object.clientIntegrationObjects.length)
if (
object.clientIntegrationObjects.every(
(intg) => !intg.isReady || intg.isReady()
)
) {
object.readyCallback();
}

if (object.toBeProcessedByIntegrationArray.length > 0) {
// send the queued events to the fetched integration
object.toBeProcessedByIntegrationArray.forEach((event) => {
const methodName = event[0];
event.shift();
// send the queued events to the fetched integration
object.toBeProcessedByIntegrationArray.forEach((event) => {
const methodName = event[0];
event.shift();

// convert common names to sdk identified name
if (Object.keys(event[0].message.integrations).length > 0) {
transformToRudderNames(event[0].message.integrations);
}
// convert common names to sdk identified name
if (Object.keys(event[0].message.integrations).length > 0) {
transformToRudderNames(event[0].message.integrations);
}

// if not specified at event level, All: true is default
const clientSuppliedIntegrations = event[0].message.integrations;

// get intersection between config plane native enabled destinations
// (which were able to successfully load on the page) vs user supplied integrations
const succesfulLoadedIntersectClientSuppliedIntegrations =
findAllEnabledDestinations(
clientSuppliedIntegrations,
object.clientIntegrationObjects
);

// send to all integrations now from the 'toBeProcessedByIntegrationArray' replay queue
for (
let i = 0;
i < succesfulLoadedIntersectClientSuppliedIntegrations.length;
i += 1
) {
try {
// if not specified at event level, All: true is default
const clientSuppliedIntegrations = event[0].message.integrations;

// get intersection between config plane native enabled destinations
// (which were able to successfully load on the page) vs user supplied integrations
const succesfulLoadedIntersectClientSuppliedIntegrations =
findAllEnabledDestinations(
clientSuppliedIntegrations,
object.clientIntegrationObjects
);

// send to all integrations now from the 'toBeProcessedByIntegrationArray' replay queue
for (
let i = 0;
i < succesfulLoadedIntersectClientSuppliedIntegrations.length;
i += 1
) {
try {
if (
!succesfulLoadedIntersectClientSuppliedIntegrations[i].isFailed ||
!succesfulLoadedIntersectClientSuppliedIntegrations[i].isFailed()
) {
if (
!succesfulLoadedIntersectClientSuppliedIntegrations[i]
.isFailed ||
!succesfulLoadedIntersectClientSuppliedIntegrations[
i
].isFailed()
succesfulLoadedIntersectClientSuppliedIntegrations[i][
methodName
]
) {
if (
succesfulLoadedIntersectClientSuppliedIntegrations[i][
methodName
]
) {
succesfulLoadedIntersectClientSuppliedIntegrations[i][
methodName
](...event);
}
succesfulLoadedIntersectClientSuppliedIntegrations[i][
methodName
](...event);
}
} catch (error) {
handleError(error);
}
} catch (error) {
handleError(error);
}
});
object.toBeProcessedByIntegrationArray = [];
}
}
});
object.toBeProcessedByIntegrationArray = [];
object.areEventsReplayed = true;
}
}
Expand Down Expand Up @@ -574,11 +565,7 @@ class Analytics {
if (event) {
rudderElement.setEventName(event);
}
if (properties) {
rudderElement.setProperty(properties);
} else {
rudderElement.setProperty({});
}
rudderElement.setProperty(properties || {});
this.trackEvent(rudderElement, options, callback);
}

Expand All @@ -598,16 +585,15 @@ class Analytics {
this.userId = userId;
this.storage.setUserId(this.userId);

const rudderElement = new RudderElementBuilder()
.setType("identify")
.build();
if (traits) {
for (const key in traits) {
this.userTraits[key] = traits[key];
}
this.storage.setUserTraits(this.userTraits);
}

const rudderElement = new RudderElementBuilder()
.setType("identify")
.build();
this.identifyUser(rudderElement, options, callback);
}

Expand Down Expand Up @@ -721,40 +707,38 @@ class Analytics {
checkReservedKeywords(rudderElement.message, type);

// structure user supplied integrations object to rudder format
if (Object.keys(rudderElement.message.integrations).length > 0) {
transformToRudderNames(rudderElement.message.integrations);
}

// if not specified at event level, All: true is default
const clientSuppliedIntegrations = rudderElement.message.integrations;

// get intersection between config plane native enabled destinations
// (which were able to successfully load on the page) vs user supplied integrations
const succesfulLoadedIntersectClientSuppliedIntegrations =
findAllEnabledDestinations(
clientSuppliedIntegrations,
this.clientIntegrationObjects
);

// try to first send to all integrations, if list populated from BE
try {
succesfulLoadedIntersectClientSuppliedIntegrations.forEach((obj) => {
if (!obj.isFailed || !obj.isFailed()) {
if (obj[type]) {
obj[type](rudderElement);
}
}
});
} catch (err) {
handleError({ message: `[sendToNative]:${err}` });
}
transformToRudderNames(rudderElement.message.integrations);

// config plane native enabled destinations, still not completely loaded
// in the page, add the events to a queue and process later
if (!this.clientIntegrationObjects) {
// logger.debug("pushing in replay queue")
// new event processing after analytics initialized but integrations not fetched from BE
this.toBeProcessedByIntegrationArray.push([type, rudderElement]);
} else {
// if not specified at event level, All: true is default
const clientSuppliedIntegrations = rudderElement.message.integrations;

// get intersection between config plane native enabled destinations
// (which were able to successfully load on the page) vs user supplied integrations
const succesfulLoadedIntersectClientSuppliedIntegrations =
findAllEnabledDestinations(
clientSuppliedIntegrations,
this.clientIntegrationObjects
);

// try to first send to all integrations, if list populated from BE
try {
succesfulLoadedIntersectClientSuppliedIntegrations.forEach((obj) => {
if (!obj.isFailed || !obj.isFailed()) {
if (obj[type]) {
obj[type](rudderElement);
}
}
});
} catch (err) {
handleError({ message: `[sendToNative]:${err}` });
}
}

// convert integrations object to server identified names, kind of hack now!
Expand Down Expand Up @@ -802,13 +786,10 @@ class Analytics {
* @param {*} rudderElement
*/
addCampaignInfo(rudderElement) {
const { search } = getDefaultPageProperties();
const campaign = this.utm(search);
if (
rudderElement.message.context &&
typeof rudderElement.message.context === "object"
) {
rudderElement.message.context.campaign = campaign;
const msgContext = rudderElement.message.context;
if (msgContext && typeof msgContext === "object") {
const { search } = getDefaultPageProperties();
rudderElement.message.context.campaign = this.utm(search);
}
}

Expand All @@ -828,10 +809,9 @@ class Analytics {
this.addCampaignInfo(rudderElement);

// assign page properties to context.page
rudderElement.message.context.page =
type == "page"
? this.getContextPageProperties(properties)
: this.getContextPageProperties();
rudderElement.message.context.page = this.getContextPageProperties(
type === "page" ? properties : undefined
);

const topLevelElements = [
"integrations",
Expand Down Expand Up @@ -965,11 +945,10 @@ class Analytics {
load(writeKey, serverUrl, options) {
// logger.debug("inside load ")
if (this.loaded) return;
let configUrl = CONFIG_URL;
if (!this.isValidWriteKey(writeKey) || !this.isValidServerUrl(serverUrl)) {
handleError({
message:
"[Analytics] load:: Unable to load due to wrong writeKey or serverUrl",
"[Analytics] load:: Unable to load due to invalid writeKey or serverUrl",
});
throw Error("failed to initialize");
}
Expand All @@ -983,16 +962,16 @@ class Analytics {
Object.assign(this.loadOnlyIntegrations, options.integrations);
transformToRudderNames(this.loadOnlyIntegrations);
}
if (options && options.configUrl) {
configUrl = getUserProvidedConfigUrl(options.configUrl);
}

if (options && options.sendAdblockPage) {
this.sendAdblockPage = true;
}
if (options && options.sendAdblockPageOptions) {
if (typeof options.sendAdblockPageOptions === "object") {
this.sendAdblockPageOptions = options.sendAdblockPageOptions;
}
if (
options &&
options.sendAdblockPageOptions &&
typeof options.sendAdblockPageOptions === "object"
) {
this.sendAdblockPageOptions = options.sendAdblockPageOptions;
}
if (options && options.clientSuppliedCallbacks) {
// convert to rudder recognized method names
Expand All @@ -1015,11 +994,13 @@ class Analytics {
this.registerCallbacks(true);
}

this.eventRepository.url = serverUrl;
this.eventRepository.writeKey = writeKey;
if (
options &&
options.queueOptions &&
options.queueOptions != null &&
typeof options.queueOptions == "object"
typeof options.queueOptions === "object"
) {
this.eventRepository.startQueue(options.queueOptions);
} else {
Expand All @@ -1030,9 +1011,6 @@ class Analytics {
this.loadIntegration = !!options.loadIntegration;
}

this.eventRepository.writeKey = writeKey;
this.eventRepository.url = serverUrl;

this.initializeUser();
this.setInitialPageProperties();
this.loaded = true;
Expand Down Expand Up @@ -1104,6 +1082,11 @@ class Analytics {
return;
}

let configUrl = CONFIG_URL;
if (options && options.configUrl) {
configUrl = getUserProvidedConfigUrl(options.configUrl);
}

try {
getJSONTrimmed(this, configUrl, writeKey, this.processResponse);
} catch (error) {
Expand Down
4 changes: 2 additions & 2 deletions integrations/ScriptLoader.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable no-use-before-define */
import logger from "../utils/logUtil";
// import logger from "../utils/logUtil";

const ScriptLoader = (id, src) => {
logger.debug(`in script loader=== ${id}`);
// logger.debug(`in script loader=== ${id}`);
const exists = document.getElementById(id);
if (exists) {
// logger.debug("script already loaded");
Expand Down

0 comments on commit 2cdf911

Please sign in to comment.