Skip to content

Commit

Permalink
separating modules from rudder client
Browse files Browse the repository at this point in the history
  • Loading branch information
prabrisha-rudder authored and sayan-rudder committed Sep 30, 2019
1 parent 8c61a8b commit 6a4eba5
Show file tree
Hide file tree
Showing 8 changed files with 391 additions and 356 deletions.
363 changes: 7 additions & 356 deletions rudder-client-javascript/RudderClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,362 +21,13 @@ var generateUUID = require("./utils.utils.js").generateUUID;
var getCurrentTimeFormatted = require("./utils.utils.js")
.getCurrentTimeFormatted;
var getJSON = require("./utils.utils.js").getJSON;

//Rudder configration class
var RudderConfig = (function() {
var instance;

function init() {
//Private variables
var endPointUri = BASE_URL;
var flushQueueSize = FLUSH_QUEUE_SIZE;
var integrations = [];

//Public methods
return {
getDefaultIntegrations: function() {
return [];
},

getEndPointUri: function() {
return endPointUri;
},

getFlushQueueSize: function() {
return this.flushQueueSize;
},

getIntegrations: function() {
return this.integrations;
},

setIntegrations: function(integrations) {
this.integrations = integrations;
return this;
},

setFlushQueueSize: function(flushQueueSize) {
this.flushQueueSize = flushQueueSize;
return this;
},

setEndPointUri: function(endPointUri) {
this.endPointUri = endPointUri;
return this;
}
};
}

return {
getDefaultConfig: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();

class AnalyticsManager {
initializeHubSpot(hubId, wrappers) {
if (typeof window !== undefined) {
/* $.ajax({
async: false,
url: "/integration/HubSpot.js",
dataType: "script"
}); */
//var _hub = new HubspotAnalyticsManager(hubId).init();
var HubspotAnalyticsManager = require("./integration/Hubspot.js");
var _hub = new HubspotAnalyticsManager();
if (_hub) {
console.log("===_hub===", _hub);
wrappers.push(_hub);
console.log("Hubspot loaded!");
}
console.log("Script loaded in sync");
}
}
}

//Event Repository
class EventRepository {
constructor(writeKey, rudderConfig, wrappers) {
this.eventsBuffer = [];
this.write_key = writeKey;
this.rudderConfig = rudderConfig;
this.enabledNativeSDK = [];
console.log(wrappers);
this.isLoaded = false;
var analyticsManager = new AnalyticsManager();
console.log("before getjson");
getJSON(
CONFIG_URL + "/source-config?write_key=" + writeKey,
wrappers,
this.isLoaded,
function(err, data, wrapperList, isLoaded) {
console.log("in callback");
if (err) {
throw new Error("unable to download configurations from server");
} else {
//parse the json response and populate the configuration JSON
var configJson = JSON.parse(data);
var enabledNativeSDK = [];
//iterate through all destinations to find which providers require
//native SDK enablement
configJson.source.destinations.forEach(function(destination, index) {
console.log(
"Destination " +
index +
" Enabled? " +
destination.enabled +
" Type: " +
destination.destinationDefinition.name +
" Use Native SDK? " +
destination.config.useNativeSDK
);
if (destination.enabled && destination.config.useNativeSDK) {
//enabledNativeSDK.push(destination.destinationDefinition.name)
switch (destination.destinationDefinition.name) {
case "HS":
var hubId = destination.config.hubId;
hubId = "6405167";
console.log("=== start init====");
analyticsManager.initializeHubSpot(hubId, wrappers);

console.log("=== end init====");
//wrapperList.push(new HubspotAnalyticsManager("6405167"));
break;
case "AF":
break;
default:
}
}
});
isLoaded = true;
}
}
);
console.log("after getjson");
}

flush(rudderElement) {
//For Javascript SDK, event will be transmitted immediately
//so buffer is really kept to be in alignment with other SDKs
this.eventsBuffer = [];

this.eventsBuffer.push(rudderElement); //Add to event buffer

//construct payload
var payload = new RudderPayload();
payload.batch = this.eventsBuffer;
payload.write_key = this.write_key;
payload.sent_at = getCurrentTimeFormatted();
//server-side integration, XHR is node module

var xhr = new XMLHttpRequest();

console.log(JSON.stringify(payload, replacer));

xhr.open("POST", this.rudderConfig.getEndPointUri(), false);
xhr.setRequestHeader("Content-Type", "application/json");

//register call back to reset event buffer on successfull POST
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
this.eventsBuffer = []; //reset event buffer
}
};
//xhr.send(JSON.stringify(payload, replacer));
}
}

//Payload class, contains batch of Elements
class RudderPayload {
constructor() {
this.batch = null;
this.write_key = null;
}
}

//Individual element class containing Rudder Message
class RudderElement {
constructor() {
this.rl_message = new RudderMessage();
}

//Setters that in turn set the field values for the contained object
setType(type) {
this.rl_message.rl_type = type;
}

setProperty(rudderProperty) {
this.rl_message.rl_properties = rudderProperty;
}

setUserProperty(rudderUserProperty) {
this.rl_message.rl_user_properties = rudderUserProperty;
}

setUserId(userId) {
this.rl_message.rl_user_id = userId;
}

setEventName(eventName) {
this.rl_message.rl_event = eventName;
}

updateTraits(traits) {
this.rl_message.rl_context.rl_traits = traits;
}
}

//Class responsible for building up the individual elements in a batch
//that is transmitted by the SDK
class RudderElementBuilder {
constructor() {
this.rudderProperty = null;
this.rudderUserProperty = null;
this.event = null;
this.userId = null;
this.channel = null;
}

//Set the property
setProperty(inputRudderProperty) {
this.rudderProperty = inputRudderProperty;
return this;
}

//Build and set the property object
setPropertyBuilder(rudderPropertyBuilder) {
this.rudderProperty = rudderPropertyBuilder.build();
return this;
}

setUserProperty(inputRudderUserProperty) {
this.rudderUserProperty = inputRudderUserProperty;
return this;
}

setUserPropertyBuilder(rudderUserPropertyBuilder) {
this.rudderUserProperty = rudderUserPropertyBuilder.build();
return this;
}

//Setter methods for all variables. Instance is returned for each call in
//accordance with the Builder pattern

setEvent(event) {
this.event = event;
return this;
}

setUserId(userId) {
this.userId = userId;
return this;
}

setChannel(channel) {
this.channel = channel;
return this;
}

build() {
var element = new RudderElement();
element.setUserId(this.userId);
element.setEventName(this.event);
element.setProperty(this.rudderProperty);
element.setUserProperty(this.rudderUserProperty);
return element;
}
}

//Core message class with default values
class RudderMessage {
constructor() {
this.rl_channel = "web";
this.rl_context = new RudderContext();
this.rl_type = null;
this.rl_action = null;
this.rl_message_id = generateUUID().toString();
this.rl_timestamp = new Date().getTime();
this.rl_anonymous_id = generateUUID().toString();
this.rl_user_id = null;
this.rl_event = null;
this.rl_properties = {};

//By default, all integrations will be set as enabled from client
//Decision to route to specific destinations will be taken at server end
this.rl_integrations = {};
this.rl_integrations["all"] = true;
}

//Get property
getProperty(key) {
return this.rl_properties[key];
}

//Add property
addProperty(key, value) {
this.rl_properties[key] = value;
}

//Validate whether this message is semantically valid for the type mentioned
validateFor(messageType) {
//First check that rl_properties is populated
if (!this.rl_properties) {
throw new Error("Key rl_properties is required");
}
//Event type specific checks
switch (messageType) {
case MessageType.TRACK:
//check if rl_event is present
if (!this.rl_event) {
throw new Error("Key rl_event is required for track event");
}
//Next make specific checks for e-commerce events
if (this.rl_event in Object.values(ECommerceEvents)) {
switch (this.rl_event) {
case ECommerceEvents.CHECKOUT_STEP_VIEWED:
case ECommerceEvents.CHECKOUT_STEP_COMPLETED:
case ECommerceEvents.PAYMENT_INFO_ENTERED:
this.checkForKey("checkout_id");
this.checkForKey("step");
break;
case ECommerceEvents.PROMOTION_VIEWED:
case ECommerceEvents.PROMOTION_CLICKED:
this.checkForKey("promotion_id");
break;
case ECommerceEvents.ORDER_REFUNDED:
this.checkForKey("order_id");
break;
default:
}
} else if (!this.rl_properties["rl_category"]) {
//if rl_category is not there, set to rl_event
this.rl_properties["rl_category"] = this.rl_event;
}

break;
case MessageType.PAGE:
break;
case MessageType.SCREEN:
if (!this.rl_properties["name"]) {
throw new Error("Key 'name' is required in rl_properties");
}
break;
}
}

//Function for checking existence of a particular property
checkForKey(propertyName) {
if (!this.rl_properties[propertyName]) {
throw new Error(
"Key '" + propertyName + "' is required in rl_properties"
);
}
}
}
var RudderConfig = require("./utils.RudderConfig.js");
var AnalyticsManager = require("./utils.AnalyticsManager.js");
var EventRepository = require("./utils.EventRepository.js");
var RudderPayload = require("./utils.RudderPayload.js");
var RudderElement = require("./utils.RudderElement.js");
var RudderElementBuilder = require("./utils.RudderElementBuilder.js");
var RudderMessage = require("./utils.RudderMessage.js");

//Context class
class RudderContext {
Expand Down
23 changes: 23 additions & 0 deletions rudder-client-javascript/utils/AnalyticsManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class AnalyticsManager {
initializeHubSpot(hubId, wrappers) {
if (typeof window !== undefined) {
/* $.ajax({
async: false,
url: "/integration/HubSpot.js",
dataType: "script"
}); */
//var _hub = new HubspotAnalyticsManager(hubId).init();
var HubspotAnalyticsManager = require("./integration/Hubspot.js");
var _hub = new HubspotAnalyticsManager(hubId).init();
if (_hub) {
console.log("===_hub===", _hub);
wrappers.push(_hub);
console.log("Hubspot loaded!");
}
console.log("Script loaded in sync");
}
}
}
module.exports = {
AnalyticsManager: AnalyticsManager
};

0 comments on commit 6a4eba5

Please sign in to comment.