Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"watch:all": "cross-env ENVIRONMENT=prod BUILDALL=true rollup --config rollup.config.js -w",
"watch:tests": "cross-env ENVIRONMENT=dev TESTTYPE=main rollup --config rollup.test.config.js -w",
"lint": "eslint src/ test/src/",
"lint:fix": "eslint src/ test/src/ --fix",
"gts:check": "gts check",
"gts:fix": "gts fix",
"prettier": "node_modules/.bin/prettier --check \"**/*.js\"",
Expand Down
80 changes: 44 additions & 36 deletions src/apiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ export interface IAPIClient {
sendSingleEventToServer: (event: SDKEvent) => void;
sendBatchForwardingStatsToServer: (
forwardingStatsData: IForwardingStatsData,
xhr: XMLHttpRequest
xhr: XMLHttpRequest,
) => void;
initializeForwarderStatsUploader: () => AsyncUploader;
prepareForwardingStats: (
forwarder: MPForwarder,
event: IUploadObject
event: IUploadObject,
) => void;
}

Expand All @@ -46,16 +46,18 @@ export interface IForwardingStatsData {
export default function APIClient(
this: IAPIClient,
mpInstance: IMParticleWebSDKInstance,
kitBlocker: KitBlocker
kitBlocker: KitBlocker,
) {
this.uploader = null;
const self = this;
this.queueEventForBatchUpload = function(event: SDKEvent) {
this.queueEventForBatchUpload = function (event: SDKEvent) {
if (!this.uploader) {
// https://go.mparticle.com/work/SQDSDKS-6317
const millis: number = parseNumber(mpInstance._Helpers.getFeatureFlag(
Constants.FeatureFlags.EventBatchingIntervalMillis
) as string);
const millis: number = parseNumber(
mpInstance._Helpers.getFeatureFlag(
Constants.FeatureFlags.EventBatchingIntervalMillis,
) as string,
);
this.uploader = new BatchUploader(mpInstance, millis);
}
this.uploader.queueEvent(event);
Expand All @@ -64,31 +66,31 @@ export default function APIClient(
mpInstance._Persistence.update();
};

this.processQueuedEvents = function() {
let mpid,
currentUser = mpInstance.Identity.getCurrentUser();
this.processQueuedEvents = function () {
let mpid;
const currentUser = mpInstance.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
if (mpInstance._Store.eventQueue.length && mpid) {
const localQueueCopy = mpInstance._Store.eventQueue;
mpInstance._Store.eventQueue = [];
this.appendUserInfoToEvents(currentUser, localQueueCopy);
localQueueCopy.forEach(function(event) {
localQueueCopy.forEach(function (event) {
self.sendEventToServer(event);
});
}
};

this.appendUserInfoToEvents = function(user, events) {
events.forEach(function(event) {
this.appendUserInfoToEvents = function (user, events) {
events.forEach(function (event) {
if (!event.MPID) {
appendUserInfo(user, event);
}
});
};

this.sendEventToServer = function(event, _options) {
this.sendEventToServer = function (event, _options) {
const defaultOptions = {
shouldUploadEvent: true,
};
Expand All @@ -97,21 +99,22 @@ export default function APIClient(
if (mpInstance._Store.webviewBridgeEnabled) {
mpInstance._NativeSdkHelpers.sendToNative(
Constants.NativeSdkPaths.LogEvent,
JSON.stringify(event)
JSON.stringify(event),
);
return;
}

let mpid,
currentUser = mpInstance.Identity.getCurrentUser();
let mpid;
const currentUser = mpInstance.Identity.getCurrentUser();
if (currentUser) {
mpid = currentUser.getMPID();
}
mpInstance._Store.requireDelay = mpInstance._Helpers.isDelayedByIntegration(
mpInstance._preInit.integrationDelays,
mpInstance._Store.integrationDelayTimeoutStart,
Date.now()
);
mpInstance._Store.requireDelay =
mpInstance._Helpers.isDelayedByIntegration(
mpInstance._preInit.integrationDelays,
mpInstance._Store.integrationDelayTimeoutStart,
Date.now(),
);
// We queue events if there is no MPID (MPID is null, or === 0), or there are integrations that that require this to stall because integration attributes
// need to be set, or if we are still fetching the config (self hosted only), and so require delaying events
if (
Expand All @@ -120,7 +123,7 @@ export default function APIClient(
!mpInstance._Store.configurationLoaded
) {
mpInstance.Logger.verbose(
'Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay.'
'Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay.',
);
mpInstance._Store.eventQueue.push(event);
return;
Expand All @@ -140,7 +143,10 @@ export default function APIClient(
// https://go.mparticle.com/work/SQDSDKS-6935
// While Event Name is 'usually' a string, there are some cases where it is a number
// in that it could be a type of MessageType Enum
if (event.EventName as unknown as number !== Types.MessageType.AppStateTransition) {
if (
(event.EventName as unknown as number) !==
Types.MessageType.AppStateTransition
) {
if (kitBlocker && kitBlocker.kitBlockingEnabled) {
event = kitBlocker.createBlockedEvent(event);
}
Expand All @@ -153,13 +159,16 @@ export default function APIClient(
}
};

this.sendBatchForwardingStatsToServer = function(forwardingStatsData, xhr) {
this.sendBatchForwardingStatsToServer = function (
forwardingStatsData,
xhr,
) {
let url;
let data;
try {
url = mpInstance._Helpers.createServiceUrl(
mpInstance._Store.SDKConfig.v2SecureServiceUrl,
mpInstance._Store.devToken
mpInstance._Store.devToken,
);
data = {
uuid: mpInstance._Helpers.generateUniqueId(),
Expand All @@ -172,18 +181,17 @@ export default function APIClient(
}
} catch (e) {
mpInstance.Logger.error(
'Error sending forwarding stats to mParticle servers.'
'Error sending forwarding stats to mParticle servers.',
);
}
};

this.initializeForwarderStatsUploader = (): AsyncUploader => {
const {
v1SecureServiceUrl: forwardingDomain,
} = mpInstance._Store.SDKConfig;
const { v1SecureServiceUrl: forwardingDomain } =
mpInstance._Store.SDKConfig;
const { devToken } = mpInstance._Store;

const uploadUrl: string = `https://${forwardingDomain}${devToken}/Forwarding`;
const uploadUrl = `https://${forwardingDomain}${devToken}/Forwarding`;

const uploader: AsyncUploader = window.fetch
? new FetchUploader(uploadUrl)
Expand All @@ -192,10 +200,10 @@ export default function APIClient(
return uploader;
};

this.prepareForwardingStats = function(
this.prepareForwardingStats = function (
forwarder: MPForwarder,
event:SDKEvent,
) : void {
event: SDKEvent,
): void {
let forwardingStatsData: IForwardingStatsData;
const queue = mpInstance._Forwarders.getForwarderStatsQueue();

Expand All @@ -213,15 +221,15 @@ export default function APIClient(
eec: event.ExpandedEventCount,
dp: event.DataPlan,
};

const {
sendSingleForwardingStatsToServer,
setForwarderStatsQueue,
} = mpInstance._Forwarders;

if (
mpInstance._Helpers.getFeatureFlag(
Constants.FeatureFlags.ReportBatching
Constants.FeatureFlags.ReportBatching,
)
) {
queue.push(forwardingStatsData);
Expand Down
4 changes: 1 addition & 3 deletions src/audience.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
export default class Audience {
public audience_id: number;

constructor(
audience_id: number,
) {
constructor(audience_id: number) {
this.audience_id = audience_id;
}
}
57 changes: 31 additions & 26 deletions src/audienceManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import {
FetchUploader,
XHRUploader,
AsyncUploader,
IFetchPayload
IFetchPayload,
} from './uploaders';
import Audience from './audience';

export interface IAudienceMembershipsServerResponse {
dt: 'cam'; // current audience memberships
dt: 'cam'; // current audience memberships
ct: number; // timestamp
id: string;
audience_memberships: Audience[];
Expand All @@ -19,23 +19,22 @@ export interface IAudienceMemberships {
}

export default class AudienceManager {
public url: string = '';
public url = '';
public userAudienceAPI: AsyncUploader;
public logger: SDKLoggerApi;

constructor(
userAudienceUrl: string,
apiKey: string,
logger: SDKLoggerApi,
) {
constructor(userAudienceUrl: string, apiKey: string, logger: SDKLoggerApi) {
this.logger = logger;
this.url = `https://${userAudienceUrl}${apiKey}/audience`;
this.userAudienceAPI = window.fetch
? new FetchUploader(this.url)
: new XHRUploader(this.url);
}

public async sendGetUserAudienceRequest(mpid: string, callback: (userAudiences: IAudienceMemberships) => void) {
public async sendGetUserAudienceRequest(
mpid: string,
callback: (userAudiences: IAudienceMemberships) => void,
) {
this.logger.verbose('Fetching user audiences from server');

const fetchPayload: IFetchPayload = {
Expand All @@ -47,42 +46,48 @@ export default class AudienceManager {
const audienceURLWithMPID = `${this.url}?mpid=${mpid}`;

try {
const userAudiencePromise: Response = await this.userAudienceAPI.upload(
fetchPayload,
audienceURLWithMPID
);
const userAudiencePromise: Response =
await this.userAudienceAPI.upload(
fetchPayload,
audienceURLWithMPID,
);

if (
userAudiencePromise.status >= 200 &&
userAudiencePromise.status < 300
) {
this.logger.verbose(`User Audiences successfully received`);

const userAudienceMembershipsServerResponse: IAudienceMembershipsServerResponse = await userAudiencePromise.json();
const userAudienceMembershipsServerResponse: IAudienceMembershipsServerResponse =
await userAudiencePromise.json();
const parsedUserAudienceMemberships: IAudienceMemberships = {
currentAudienceMemberships: userAudienceMembershipsServerResponse?.audience_memberships
}
currentAudienceMemberships:
userAudienceMembershipsServerResponse?.audience_memberships,
};

try {
callback(parsedUserAudienceMemberships);
} catch(e) {
throw new Error('Error invoking callback on user audience response.');
} catch (e) {
throw new Error(
'Error invoking callback on user audience response.',
);
}

} else if (userAudiencePromise.status === 401) {
throw new Error('`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`');
throw new Error(
'`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`',
);
} else if (userAudiencePromise.status === 403) {
throw new Error('`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`');
throw new Error(
'`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`',
);
} else {
// In case there is an HTTP error we did not anticipate.
throw new Error(
`Uncaught HTTP Error ${userAudiencePromise.status}.`
`Uncaught HTTP Error ${userAudiencePromise.status}.`,
);
}
} catch (e) {
this.logger.error(
`Error retrieving audiences. ${e}`
);
this.logger.error(`Error retrieving audiences. ${e}`);
}
}
}
}
Loading
Loading