Skip to content

Commit 69c18f7

Browse files
authored
feat: add more interface for flutter web support (#444)
* feat: add more interface for flutter web support * patch: code clean up and other fix * test: add setUserId test * patch: test update * patch: remove unnecessary api interface * patch: make setLibrary function able to seprate set library name and version * patch: make setLibrary function able to seprate set library name and version
1 parent 4659419 commit 69c18f7

File tree

3 files changed

+486
-7
lines changed

3 files changed

+486
-7
lines changed

src/amplitude-client.js

+207-7
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import base64Id from './base64Id';
1717
import DEFAULT_OPTIONS from './options';
1818
import getHost from './get-host';
1919
import baseCookie from './base-cookie';
20-
import { getEventLogApi } from './server-zone';
20+
import { AmplitudeServerZone, getEventLogApi } from './server-zone';
2121
import ConfigManager from './config-manager';
2222

2323
/**
@@ -858,15 +858,33 @@ AmplitudeClient.prototype.setDomain = function setDomain(domain) {
858858
* Sets an identifier for the current user.
859859
* @public
860860
* @param {string} userId - identifier to set. Can be null.
861+
* @param {boolean} startNewSession - (optional) if start a new session or not
861862
* @example amplitudeClient.setUserId('[email protected]');
862863
*/
863-
AmplitudeClient.prototype.setUserId = function setUserId(userId) {
864+
AmplitudeClient.prototype.setUserId = function setUserId(userId, startNewSession = false) {
865+
if (!utils.validateInput(startNewSession, 'startNewSession', 'boolean')) {
866+
return;
867+
}
868+
864869
if (this._shouldDeferCall()) {
865870
return this._q.push(['setUserId'].concat(Array.prototype.slice.call(arguments, 0)));
866871
}
867872

868873
try {
869874
this.options.userId = (userId !== undefined && userId !== null && '' + userId) || null;
875+
if (startNewSession) {
876+
if (this.options.unsetParamsReferrerOnNewSession) {
877+
this._unsetUTMParams();
878+
}
879+
this._newSession = true;
880+
this._sessionId = new Date().getTime();
881+
882+
// only capture UTM params and referrer if new session
883+
if (this.options.saveParamsReferrerOncePerSession) {
884+
this._trackParamsAndReferrer();
885+
}
886+
}
887+
870888
_saveCookieData(this);
871889
} catch (e) {
872890
utils.log.error(e);
@@ -1232,6 +1250,7 @@ AmplitudeClient.prototype._logEvent = function _logEvent(
12321250
timestamp,
12331251
callback,
12341252
errorCallback,
1253+
outOfSession,
12351254
) {
12361255
_loadCookieData(this); // reload cookie before each log event to sync event meta-data between windows and tabs
12371256

@@ -1257,7 +1276,13 @@ AmplitudeClient.prototype._logEvent = function _logEvent(
12571276
}
12581277
var sequenceNumber = this.nextSequenceNumber();
12591278
var eventTime = type(timestamp) === 'number' ? timestamp : new Date().getTime();
1260-
if (!this._sessionId || !this._lastEventTime || eventTime - this._lastEventTime > this.options.sessionTimeout) {
1279+
if (outOfSession) {
1280+
this._sessionId = -1;
1281+
} else if (
1282+
!this._sessionId ||
1283+
!this._lastEventTime ||
1284+
eventTime - this._lastEventTime > this.options.sessionTimeout
1285+
) {
12611286
this._sessionId = eventTime;
12621287
}
12631288
this._lastEventTime = eventTime;
@@ -1383,13 +1408,20 @@ AmplitudeClient.prototype._limitEventsQueued = function _limitEventsQueued(queue
13831408
* @param {Amplitude~eventCallback} opt_error_callback - (optional) a callback function to run after the event logging
13841409
* fails. The failure can be from the request being malformed or from a network failure
13851410
* Note: the server response code and response body from the event upload are passed to the callback function.
1411+
* @param {boolean} outOfSession - (optional) if this event is out of session or not
13861412
* @example amplitudeClient.logEvent('Clicked Homepage Button', {'finished_flow': false, 'clicks': 15});
13871413
*/
1388-
AmplitudeClient.prototype.logEvent = function logEvent(eventType, eventProperties, opt_callback, opt_error_callback) {
1414+
AmplitudeClient.prototype.logEvent = function logEvent(
1415+
eventType,
1416+
eventProperties,
1417+
opt_callback,
1418+
opt_error_callback,
1419+
outOfSession = false,
1420+
) {
13891421
if (this._shouldDeferCall()) {
13901422
return this._q.push(['logEvent'].concat(Array.prototype.slice.call(arguments, 0)));
13911423
}
1392-
return this.logEventWithTimestamp(eventType, eventProperties, null, opt_callback, opt_error_callback);
1424+
return this.logEventWithTimestamp(eventType, eventProperties, null, opt_callback, opt_error_callback, outOfSession);
13931425
};
13941426

13951427
/**
@@ -1403,6 +1435,7 @@ AmplitudeClient.prototype.logEvent = function logEvent(eventType, eventPropertie
14031435
* @param {Amplitude~eventCallback} opt_error_callback - (optional) a callback function to run after the event logging
14041436
* fails. The failure can be from the request being malformed or from a network failure
14051437
* Note: the server response code and response body from the event upload are passed to the callback function.
1438+
* @param {boolean} outOfSession - (optional) if out of the sessioin or not
14061439
* @example amplitudeClient.logEvent('Clicked Homepage Button', {'finished_flow': false, 'clicks': 15});
14071440
*/
14081441
AmplitudeClient.prototype.logEventWithTimestamp = function logEvent(
@@ -1411,6 +1444,7 @@ AmplitudeClient.prototype.logEventWithTimestamp = function logEvent(
14111444
timestamp,
14121445
opt_callback,
14131446
opt_error_callback,
1447+
outOfSession = false,
14141448
) {
14151449
if (this._shouldDeferCall()) {
14161450
return this._q.push(['logEventWithTimestamp'].concat(Array.prototype.slice.call(arguments, 0)));
@@ -1435,6 +1469,13 @@ AmplitudeClient.prototype.logEventWithTimestamp = function logEvent(
14351469
});
14361470
return -1;
14371471
}
1472+
1473+
if (!utils.validateInput(outOfSession, 'outOfSession', 'boolean')) {
1474+
_logErrorsWithCallbacks(opt_callback, opt_error_callback, 0, 'No request sent', {
1475+
reason: 'Invalid outOfSession value',
1476+
});
1477+
}
1478+
14381479
return this._logEvent(
14391480
eventType,
14401481
eventProperties,
@@ -1445,6 +1486,7 @@ AmplitudeClient.prototype.logEventWithTimestamp = function logEvent(
14451486
timestamp,
14461487
opt_callback,
14471488
opt_error_callback,
1489+
outOfSession,
14481490
);
14491491
};
14501492

@@ -1473,6 +1515,7 @@ AmplitudeClient.prototype.logEventWithGroups = function (
14731515
groups,
14741516
opt_callback,
14751517
opt_error_callback,
1518+
outOfSession = false,
14761519
) {
14771520
if (this._shouldDeferCall()) {
14781521
return this._q.push(['logEventWithGroups'].concat(Array.prototype.slice.call(arguments, 0)));
@@ -1490,7 +1533,25 @@ AmplitudeClient.prototype.logEventWithGroups = function (
14901533
});
14911534
return -1;
14921535
}
1493-
return this._logEvent(eventType, eventProperties, null, null, groups, null, null, opt_callback, opt_error_callback);
1536+
1537+
if (!utils.validateInput(outOfSession, 'outOfSession', 'boolean')) {
1538+
_logErrorsWithCallbacks(event.callback, event.errorCallback, 0, 'No request sent', {
1539+
reason: 'Invalid outOfSession value',
1540+
});
1541+
}
1542+
1543+
return this._logEvent(
1544+
eventType,
1545+
eventProperties,
1546+
null,
1547+
null,
1548+
groups,
1549+
null,
1550+
null,
1551+
opt_callback,
1552+
opt_error_callback,
1553+
outOfSession,
1554+
);
14941555
};
14951556

14961557
/**
@@ -1847,7 +1908,10 @@ AmplitudeClient.prototype.__VERSION__ = function getVersion() {
18471908
* @param {string} name - Custom library name
18481909
* @param {string} version - Custom library version
18491910
*/
1850-
AmplitudeClient.prototype.setLibrary = function setLibrary(name, version) {
1911+
AmplitudeClient.prototype.setLibrary = function setLibrary(
1912+
name = this.options.libraryName,
1913+
version = this.options.libraryVersion,
1914+
) {
18511915
this.options.library = { name: name, version: version };
18521916
};
18531917

@@ -1897,4 +1961,140 @@ AmplitudeClient.prototype._refreshDynamicConfig = function _refreshDynamicConfig
18971961
}
18981962
};
18991963

1964+
/**
1965+
* Returns the deviceId value.
1966+
* @public
1967+
* @return {string} Id of current device.
1968+
*/
1969+
AmplitudeClient.prototype.getDeviceId = function getDeviceId() {
1970+
return this.options.deviceId;
1971+
};
1972+
1973+
/**
1974+
* Returns the userId.
1975+
* @public
1976+
* @return {string} Id of current user.
1977+
*/
1978+
AmplitudeClient.prototype.getUserId = function getUserId() {
1979+
return this.options.userId;
1980+
};
1981+
1982+
/**
1983+
* Set a custom session expiration time.
1984+
* @public
1985+
* @param {number} timeInMillis - session expireation time in milliseconds.
1986+
*/
1987+
AmplitudeClient.prototype.setMinTimeBetweenSessionsMillis = function setMinTimeBetweenSessionsMillis(timeInMillis) {
1988+
if (!utils.validateInput(timeInMillis, 'timeInMillis', 'number')) {
1989+
return;
1990+
}
1991+
1992+
if (this._shouldDeferCall()) {
1993+
return this._q.push(['setMinTimeBetweenSessionsMillis'].concat(Array.prototype.slice.call(arguments, 0)));
1994+
}
1995+
1996+
try {
1997+
this.options.sessionTimeout = timeInMillis;
1998+
} catch (e) {
1999+
utils.log.error(e);
2000+
}
2001+
};
2002+
2003+
/**
2004+
* Sets minimum number of events to batch together per request if batchEvents is true.
2005+
* @public
2006+
* @param {number} eventUploadThreshold - The number of the event upload threshold. Default value is 30.
2007+
* @example amplitudeClient.setEventUploadThreshold(10);
2008+
*/
2009+
AmplitudeClient.prototype.setEventUploadThreshold = function setEventUploadThreshold(eventUploadThreshold) {
2010+
if (!utils.validateInput(eventUploadThreshold, 'eventUploadThreshold', 'number')) {
2011+
return;
2012+
}
2013+
2014+
if (this._shouldDeferCall()) {
2015+
return this._q.push(['setEventUploadThreshold'].concat(Array.prototype.slice.call(arguments, 0)));
2016+
}
2017+
2018+
try {
2019+
this.options.eventUploadThreshold = eventUploadThreshold;
2020+
} catch (e) {
2021+
utils.log.error(e);
2022+
}
2023+
};
2024+
2025+
/**
2026+
* Dynamically adjust server URL
2027+
* @public
2028+
* @param {bool} useDynamicConfig - if enable dynamic config or not.
2029+
* @example amplitudeClient.setUseDynamicConfig(true);
2030+
*/
2031+
AmplitudeClient.prototype.setUseDynamicConfig = function setUseDynamicConfig(useDynamicConfig) {
2032+
if (!utils.validateInput(useDynamicConfig, 'useDynamicConfig', 'boolean')) {
2033+
return;
2034+
}
2035+
2036+
if (this._shouldDeferCall()) {
2037+
return this._q.push(['setUseDynamicConfig'].concat(Array.prototype.slice.call(arguments, 0)));
2038+
}
2039+
2040+
try {
2041+
this.options.useDynamicConfig = useDynamicConfig;
2042+
this._refreshDynamicConfig();
2043+
} catch (e) {
2044+
utils.log.error(e);
2045+
}
2046+
};
2047+
2048+
/**
2049+
* Sets the server zone, used for server api endpoint and dynamic configuration.
2050+
* @public
2051+
* @param {string} serverZone - the server zone value. AmplitudeServerZone.US or AmplitudeServerZone.EU.
2052+
* @param {bool} serverZoneBasedApi - (optional) update api endpoint with serverZone change or not. For data residency, recommend to enable it unless using own proxy server.
2053+
* @example amplitudeClient.setServerZone('[email protected]', true);
2054+
*/
2055+
AmplitudeClient.prototype.setServerZone = function setServerZone(serverZone, serverZoneBasedApi = true) {
2056+
if (
2057+
(serverZone !== AmplitudeServerZone.EU && serverZone !== AmplitudeServerZone.US) ||
2058+
!utils.validateInput(serverZoneBasedApi, 'serverZoneBasedApi', 'boolean')
2059+
) {
2060+
return;
2061+
}
2062+
2063+
if (this._shouldDeferCall()) {
2064+
return this._q.push(['setServerZone'].concat(Array.prototype.slice.call(arguments, 0)));
2065+
}
2066+
2067+
try {
2068+
this.options.serverZone = serverZone;
2069+
this.options.serverZoneBasedApi = serverZoneBasedApi;
2070+
if (serverZoneBasedApi) {
2071+
this.options.apiEndpoint = getEventLogApi(this.options.serverZone);
2072+
}
2073+
} catch (e) {
2074+
utils.log.error(e);
2075+
}
2076+
};
2077+
2078+
/**
2079+
* Sets the server URL for the request.
2080+
* @public
2081+
* @param {string} serverUrl - The value of the server URL.
2082+
* @example amplitudeClient.setServerUrl('api.amplitude.com');
2083+
*/
2084+
AmplitudeClient.prototype.setServerUrl = function setServerUrl(serverUrl) {
2085+
if (!utils.validateInput(serverUrl, 'serverUrl', 'string')) {
2086+
return;
2087+
}
2088+
2089+
if (this._shouldDeferCall()) {
2090+
return this._q.push(['setServerUrl'].concat(Array.prototype.slice.call(arguments, 0)));
2091+
}
2092+
2093+
try {
2094+
this.options.apiEndpoint = serverUrl;
2095+
} catch (e) {
2096+
utils.log.error(e);
2097+
}
2098+
};
2099+
19002100
export default AmplitudeClient;

src/amplitude-snippet.js

+8
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,14 @@
7979
'logEventWithGroups',
8080
'setSessionId',
8181
'resetSessionId',
82+
'getDeviceId',
83+
'getUserId',
84+
'setMinTimeBetweenSessionsMillis',
85+
'setEventUploadThreshold',
86+
'setUseDynamicConfig',
87+
'setServerZone',
88+
'setServerUrl',
89+
'sendEvents',
8290
'setLibrary',
8391
'setTransport',
8492
];

0 commit comments

Comments
 (0)