@appbaseio/analytics
Advanced tools
Comparing version 1.0.0-alpha.1 to 2.0.0-beta
@@ -25,58 +25,3 @@ 'use strict'; | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
} | ||
function _toPrimitive(input, hint) { | ||
if (typeof input !== "object" || input === null) return input; | ||
var prim = input[Symbol.toPrimitive]; | ||
if (prim !== undefined) { | ||
var res = prim.call(input, hint || "default"); | ||
if (typeof res !== "object") return res; | ||
throw new TypeError("@@toPrimitive must return a primitive value."); | ||
} | ||
return (hint === "string" ? String : Number)(input); | ||
} | ||
function _toPropertyKey(arg) { | ||
var key = _toPrimitive(arg, "string"); | ||
return typeof key === "symbol" ? key : String(key); | ||
} | ||
/** | ||
* Function to parse the headers to a string | ||
*/ | ||
function parseHeaders(headers) { | ||
var finalStr = ''; | ||
if (headers) { | ||
Object.keys(headers).forEach(function (key, index) { | ||
finalStr += key + "=" + headers[key]; | ||
if (index < Object.keys(headers).length - 1) { | ||
finalStr += ','; | ||
} | ||
}); | ||
} | ||
return finalStr; | ||
} // Function to parse the URL | ||
function getURL(url) { | ||
return url && url.trim() !== '' ? url : 'https://scalr.api.appbase.io'; | ||
} | ||
// Function to parse the URL | ||
function btoa(input) { | ||
@@ -106,22 +51,34 @@ if (input === void 0) { | ||
function AppbaseAnalytics(config) { | ||
if (config === void 0) { | ||
config = {}; | ||
function validateIndex(index) { | ||
if (!index) { | ||
throw new Error('appbase-analytics: A valid index must be present to record analytics events.'); | ||
} | ||
this.index = config.index; | ||
this.credentials = config.credentials; | ||
this.url = getURL(config.url); | ||
this.userID = config.userID; | ||
this.customEvents = config.customEvents; | ||
this.searchQuery = undefined; | ||
this.searchID = undefined; | ||
this.searchState = null; | ||
this.filters = null; | ||
this.emptyQuery = config.emptyQuery !== undefined ? config.emptyQuery : true; // custom headers | ||
this.headers = null; | ||
} | ||
function validateCredentials(credentials) { | ||
if (!credentials) { | ||
throw new Error('appbase-analytics: Auth credentials is missing.'); | ||
} | ||
} | ||
function validateURL(url) { | ||
if (!url) { | ||
throw new Error('appbase-analytics: URL is missing.'); | ||
} | ||
} | ||
function validateQuery(query, queryID) { | ||
if ((query === undefined || query === null) && !queryID) { | ||
throw new Error('appbase-analytics: query or queryID must be present to register a click/conversion event'); | ||
} | ||
} | ||
function validateClickObjects(objects) { | ||
if (!objects || Object.keys(objects).length < 1) { | ||
throw new Error('appbase-analytics: at least one click object must be present to register a click event'); | ||
} | ||
} | ||
function validateConversionObjects(objects) { | ||
if (!objects || Object.keys(objects).length < 1) { | ||
throw new Error('appbase-analytics: at least one click object must be present to register a click event'); | ||
} | ||
} | ||
function index (config) { | ||
function initClient(config) { | ||
if (config === void 0) { | ||
@@ -131,200 +88,129 @@ config = {}; | ||
var client = new AppbaseAnalytics(config); | ||
AppbaseAnalytics.prototype.setIndex = function (index) { | ||
this.index = index; | ||
return this; | ||
var metrics = { | ||
credentials: config.credentials, | ||
index: config.index, | ||
url: config.url, | ||
userID: config.userID, | ||
globalEventData: config.globalEventData, | ||
queryID: '', | ||
headers: null | ||
}; | ||
validateIndex(metrics.index); | ||
validateCredentials(metrics.credentials); | ||
validateURL(metrics.url); | ||
AppbaseAnalytics.prototype.setCredentials = function (credentials) { | ||
this.credentials = credentials; | ||
return this; | ||
}; | ||
metrics._request = function (url, body, callback) { | ||
return fetch(metrics.url + "/" + metrics.index + "/_analytics/" + url, { | ||
method: 'PUT', | ||
headers: _extends({}, metrics.headers, { | ||
'Content-Type': 'application/json', | ||
Authorization: "Basic " + btoa(metrics.credentials) | ||
}), | ||
body: JSON.stringify(body) | ||
}).then(function (response) { | ||
if (callback) { | ||
callback(null, response); | ||
} | ||
})["catch"](function (err) { | ||
console.error(err); | ||
AppbaseAnalytics.prototype.setURL = function (url) { | ||
this.url = getURL(url); | ||
return this; | ||
}; | ||
if (callback) { | ||
callback(err, null); | ||
} | ||
}); | ||
}; // To register a search | ||
AppbaseAnalytics.prototype.setHeaders = function (headers) { | ||
this.headers = headers; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.setSearchQuery = function (searchQuery) { | ||
this.searchQuery = searchQuery; | ||
return this; | ||
}; | ||
metrics.search = function (searchConfig, callback) { | ||
validateQuery(searchConfig.query); | ||
AppbaseAnalytics.prototype.clearSearchQuery = function () { | ||
this.searchQuery = undefined; | ||
return this; | ||
}; | ||
var captureQueryID = function captureQueryID(err, res) { | ||
if (res) { | ||
res.json().then(function (response) { | ||
if (response && response.query_id) { | ||
metrics.queryID = response.query_id; | ||
} | ||
})["catch"](function (error) { | ||
console.error(error); | ||
}); | ||
} | ||
AppbaseAnalytics.prototype.setSearchID = function (searchID) { | ||
this.searchID = searchID; | ||
return this; | ||
}; | ||
if (callback) { | ||
callback(err, res); | ||
} | ||
}; // just to avoid the flow type error | ||
AppbaseAnalytics.prototype.clearSearchID = function () { | ||
this.searchID = undefined; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.setSearchState = function (searchState) { | ||
this.searchState = searchState; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
query: searchConfig.query, | ||
event_data: searchConfig.eventData, | ||
filters: searchConfig.filters, | ||
hits: searchConfig.hits, | ||
user_id: searchConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.clearSearchState = function () { | ||
this.searchState = null; | ||
return this; | ||
}; | ||
metrics._request('search', requestBody, captureQueryID); | ||
} | ||
}; // To register a click | ||
AppbaseAnalytics.prototype.setUserID = function (userID) { | ||
this.userID = userID; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.clearUserID = function () { | ||
this.userID = null; | ||
return this; | ||
}; | ||
metrics.click = function (clickConfig, callback) { | ||
validateQuery(clickConfig.query, clickConfig.queryID); | ||
validateClickObjects(clickConfig.objects); // just to avoid the flow type error | ||
AppbaseAnalytics.prototype.setCustomEvents = function (customEvents) { | ||
this.customEvents = customEvents; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
click_on: clickConfig.objects, | ||
click_type: clickConfig.type || 'result', | ||
query: clickConfig.query, | ||
query_id: clickConfig.queryID, | ||
event_data: clickConfig.eventData, | ||
user_id: clickConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.clearCustomEvents = function () { | ||
this.customEvents = null; | ||
return this; | ||
}; | ||
metrics._request('click', requestBody, callback); | ||
} | ||
}; // To register a conversion | ||
AppbaseAnalytics.prototype.addCustomEvent = function (customEvent) { | ||
this.customEvents = _extends({}, this.customEvents, { | ||
customEvent: customEvent | ||
}); | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.removeCustomEvent = function (eventKey) { | ||
var _this$customEvents = this.customEvents, | ||
del = _this$customEvents[eventKey], | ||
rest = _objectWithoutPropertiesLoose(_this$customEvents, [eventKey].map(_toPropertyKey)); | ||
metrics.conversion = function (conversionConfig, callback) { | ||
validateQuery(conversionConfig.query, conversionConfig.queryID); | ||
validateConversionObjects(conversionConfig.objects); // just to avoid the flow type error | ||
this.customEvents = rest; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
conversion_on: conversionConfig.objects, | ||
query: conversionConfig.query, | ||
query_id: conversionConfig.queryID, | ||
event_data: conversionConfig.eventData, | ||
user_id: conversionConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.setFilters = function (filters) { | ||
this.filters = filters; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.clearFilters = function () { | ||
this.filters = null; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.addFilter = function (filter) { | ||
this.filters = _extends({}, this.filters, { | ||
filter: filter | ||
}); | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.removeFilter = function (filterKey) { | ||
var _this$filters = this.filters, | ||
del = _this$filters[filterKey], | ||
rest = _objectWithoutPropertiesLoose(_this$filters, [filterKey].map(_toPropertyKey)); | ||
this.filters = rest; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.enableEmptyQuery = function () { | ||
this.emptyQuery = true; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.disableEmptyQuery = function () { | ||
this.emptyQuery = false; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.registerClick = function (clickPosition, isSuggestion) { | ||
if (Number.isNaN(parseInt(clickPosition, 10))) { | ||
throw new Error('appbase-analytics: click position must be an integer.'); | ||
metrics._request('conversion', requestBody, callback); | ||
} | ||
}; // Sets the userID | ||
var commonHeaders = this._recordEventHeaders(); | ||
return fetch(this.url + "/" + this.index + "/_analytics", { | ||
method: 'POST', | ||
headers: _extends({}, commonHeaders, {}, isSuggestion ? { | ||
'X-Search-Suggestions-Click': true, | ||
'X-Search-Suggestions-ClickPosition': clickPosition | ||
} : { | ||
'X-Search-Click': true, | ||
'X-Search-ClickPosition': clickPosition | ||
}) | ||
}); | ||
}; | ||
metrics.setUserID = function (userID) { | ||
metrics.userID = userID; | ||
}; // Sets the global events | ||
AppbaseAnalytics.prototype.registerConversion = function () { | ||
var commonHeaders = this._recordEventHeaders(); | ||
return fetch(this.url + "/" + this.index + "/_analytics", { | ||
method: 'POST', | ||
headers: _extends({}, commonHeaders, { | ||
'X-Search-Conversion': true | ||
}) | ||
}); | ||
}; // Headers value will be based on the analytics current state, may or may not present | ||
metrics.setGlobalEventData = function (globalEvents) { | ||
metrics.globalEventData = globalEvents; | ||
}; // Sets the headers | ||
AppbaseAnalytics.prototype.getAnalyticsHeaders = function () { | ||
return _extends({}, this.searchQuery || this.emptyQuery ? { | ||
'X-Search-Query': this.searchQuery || '' | ||
} : null, {}, this.searchID ? { | ||
'X-Search-Id': this.searchID | ||
} : null, {}, this.searchState ? { | ||
'X-Search-State': JSON.stringify(this.searchState) | ||
} : null, {}, this.userID ? { | ||
'X-User-Id': this.userID | ||
} : null, {}, this.customEvents ? { | ||
'X-Search-CustomEvent': parseHeaders(this.customEvents) | ||
} : null, {}, this.filters ? { | ||
'X-Search-Filters': parseHeaders(this.filters) | ||
} : null); | ||
metrics.setHeaders = function (headers) { | ||
metrics.headers = headers; | ||
}; | ||
AppbaseAnalytics.prototype._recordEventHeaders = function () { | ||
if (!this.index) { | ||
throw new Error('appbase-analytics: A valid index must be present to record an event.'); | ||
} | ||
return metrics; | ||
} | ||
if (!this.credentials) { | ||
throw new Error('appbase-analytics: Auth credentials is missing.'); | ||
} | ||
var index = { | ||
init: initClient | ||
}; | ||
if (!this.searchID) { | ||
throw new Error('appbase-analytics: searchID must be present to record an event.'); | ||
} | ||
return _extends({}, this.headers, { | ||
'Content-Type': 'application/json', | ||
Authorization: "Basic " + btoa(this.credentials), | ||
'X-Search-Id': this.searchID | ||
}, this.userID ? { | ||
'X-User-Id': this.userID | ||
} : null, {}, this.customEvents ? { | ||
'X-Search-CustomEvent': parseHeaders(this.customEvents) | ||
} : null); | ||
}; | ||
return client; | ||
} | ||
module.exports = index; |
@@ -21,58 +21,3 @@ import fetch from 'cross-fetch'; | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
} | ||
function _toPrimitive(input, hint) { | ||
if (typeof input !== "object" || input === null) return input; | ||
var prim = input[Symbol.toPrimitive]; | ||
if (prim !== undefined) { | ||
var res = prim.call(input, hint || "default"); | ||
if (typeof res !== "object") return res; | ||
throw new TypeError("@@toPrimitive must return a primitive value."); | ||
} | ||
return (hint === "string" ? String : Number)(input); | ||
} | ||
function _toPropertyKey(arg) { | ||
var key = _toPrimitive(arg, "string"); | ||
return typeof key === "symbol" ? key : String(key); | ||
} | ||
/** | ||
* Function to parse the headers to a string | ||
*/ | ||
function parseHeaders(headers) { | ||
var finalStr = ''; | ||
if (headers) { | ||
Object.keys(headers).forEach(function (key, index) { | ||
finalStr += key + "=" + headers[key]; | ||
if (index < Object.keys(headers).length - 1) { | ||
finalStr += ','; | ||
} | ||
}); | ||
} | ||
return finalStr; | ||
} // Function to parse the URL | ||
function getURL(url) { | ||
return url && url.trim() !== '' ? url : 'https://scalr.api.appbase.io'; | ||
} | ||
// Function to parse the URL | ||
function btoa(input) { | ||
@@ -102,22 +47,34 @@ if (input === void 0) { | ||
function AppbaseAnalytics(config) { | ||
if (config === void 0) { | ||
config = {}; | ||
function validateIndex(index) { | ||
if (!index) { | ||
throw new Error('appbase-analytics: A valid index must be present to record analytics events.'); | ||
} | ||
this.index = config.index; | ||
this.credentials = config.credentials; | ||
this.url = getURL(config.url); | ||
this.userID = config.userID; | ||
this.customEvents = config.customEvents; | ||
this.searchQuery = undefined; | ||
this.searchID = undefined; | ||
this.searchState = null; | ||
this.filters = null; | ||
this.emptyQuery = config.emptyQuery !== undefined ? config.emptyQuery : true; // custom headers | ||
this.headers = null; | ||
} | ||
function validateCredentials(credentials) { | ||
if (!credentials) { | ||
throw new Error('appbase-analytics: Auth credentials is missing.'); | ||
} | ||
} | ||
function validateURL(url) { | ||
if (!url) { | ||
throw new Error('appbase-analytics: URL is missing.'); | ||
} | ||
} | ||
function validateQuery(query, queryID) { | ||
if ((query === undefined || query === null) && !queryID) { | ||
throw new Error('appbase-analytics: query or queryID must be present to register a click/conversion event'); | ||
} | ||
} | ||
function validateClickObjects(objects) { | ||
if (!objects || Object.keys(objects).length < 1) { | ||
throw new Error('appbase-analytics: at least one click object must be present to register a click event'); | ||
} | ||
} | ||
function validateConversionObjects(objects) { | ||
if (!objects || Object.keys(objects).length < 1) { | ||
throw new Error('appbase-analytics: at least one click object must be present to register a click event'); | ||
} | ||
} | ||
function index (config) { | ||
function initClient(config) { | ||
if (config === void 0) { | ||
@@ -127,200 +84,129 @@ config = {}; | ||
var client = new AppbaseAnalytics(config); | ||
AppbaseAnalytics.prototype.setIndex = function (index) { | ||
this.index = index; | ||
return this; | ||
var metrics = { | ||
credentials: config.credentials, | ||
index: config.index, | ||
url: config.url, | ||
userID: config.userID, | ||
globalEventData: config.globalEventData, | ||
queryID: '', | ||
headers: null | ||
}; | ||
validateIndex(metrics.index); | ||
validateCredentials(metrics.credentials); | ||
validateURL(metrics.url); | ||
AppbaseAnalytics.prototype.setCredentials = function (credentials) { | ||
this.credentials = credentials; | ||
return this; | ||
}; | ||
metrics._request = function (url, body, callback) { | ||
return fetch(metrics.url + "/" + metrics.index + "/_analytics/" + url, { | ||
method: 'PUT', | ||
headers: _extends({}, metrics.headers, { | ||
'Content-Type': 'application/json', | ||
Authorization: "Basic " + btoa(metrics.credentials) | ||
}), | ||
body: JSON.stringify(body) | ||
}).then(function (response) { | ||
if (callback) { | ||
callback(null, response); | ||
} | ||
})["catch"](function (err) { | ||
console.error(err); | ||
AppbaseAnalytics.prototype.setURL = function (url) { | ||
this.url = getURL(url); | ||
return this; | ||
}; | ||
if (callback) { | ||
callback(err, null); | ||
} | ||
}); | ||
}; // To register a search | ||
AppbaseAnalytics.prototype.setHeaders = function (headers) { | ||
this.headers = headers; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.setSearchQuery = function (searchQuery) { | ||
this.searchQuery = searchQuery; | ||
return this; | ||
}; | ||
metrics.search = function (searchConfig, callback) { | ||
validateQuery(searchConfig.query); | ||
AppbaseAnalytics.prototype.clearSearchQuery = function () { | ||
this.searchQuery = undefined; | ||
return this; | ||
}; | ||
var captureQueryID = function captureQueryID(err, res) { | ||
if (res) { | ||
res.json().then(function (response) { | ||
if (response && response.query_id) { | ||
metrics.queryID = response.query_id; | ||
} | ||
})["catch"](function (error) { | ||
console.error(error); | ||
}); | ||
} | ||
AppbaseAnalytics.prototype.setSearchID = function (searchID) { | ||
this.searchID = searchID; | ||
return this; | ||
}; | ||
if (callback) { | ||
callback(err, res); | ||
} | ||
}; // just to avoid the flow type error | ||
AppbaseAnalytics.prototype.clearSearchID = function () { | ||
this.searchID = undefined; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.setSearchState = function (searchState) { | ||
this.searchState = searchState; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
query: searchConfig.query, | ||
event_data: searchConfig.eventData, | ||
filters: searchConfig.filters, | ||
hits: searchConfig.hits, | ||
user_id: searchConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.clearSearchState = function () { | ||
this.searchState = null; | ||
return this; | ||
}; | ||
metrics._request('search', requestBody, captureQueryID); | ||
} | ||
}; // To register a click | ||
AppbaseAnalytics.prototype.setUserID = function (userID) { | ||
this.userID = userID; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.clearUserID = function () { | ||
this.userID = null; | ||
return this; | ||
}; | ||
metrics.click = function (clickConfig, callback) { | ||
validateQuery(clickConfig.query, clickConfig.queryID); | ||
validateClickObjects(clickConfig.objects); // just to avoid the flow type error | ||
AppbaseAnalytics.prototype.setCustomEvents = function (customEvents) { | ||
this.customEvents = customEvents; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
click_on: clickConfig.objects, | ||
click_type: clickConfig.type || 'result', | ||
query: clickConfig.query, | ||
query_id: clickConfig.queryID, | ||
event_data: clickConfig.eventData, | ||
user_id: clickConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.clearCustomEvents = function () { | ||
this.customEvents = null; | ||
return this; | ||
}; | ||
metrics._request('click', requestBody, callback); | ||
} | ||
}; // To register a conversion | ||
AppbaseAnalytics.prototype.addCustomEvent = function (customEvent) { | ||
this.customEvents = _extends({}, this.customEvents, { | ||
customEvent: customEvent | ||
}); | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.removeCustomEvent = function (eventKey) { | ||
var _this$customEvents = this.customEvents, | ||
del = _this$customEvents[eventKey], | ||
rest = _objectWithoutPropertiesLoose(_this$customEvents, [eventKey].map(_toPropertyKey)); | ||
metrics.conversion = function (conversionConfig, callback) { | ||
validateQuery(conversionConfig.query, conversionConfig.queryID); | ||
validateConversionObjects(conversionConfig.objects); // just to avoid the flow type error | ||
this.customEvents = rest; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
conversion_on: conversionConfig.objects, | ||
query: conversionConfig.query, | ||
query_id: conversionConfig.queryID, | ||
event_data: conversionConfig.eventData, | ||
user_id: conversionConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.setFilters = function (filters) { | ||
this.filters = filters; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.clearFilters = function () { | ||
this.filters = null; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.addFilter = function (filter) { | ||
this.filters = _extends({}, this.filters, { | ||
filter: filter | ||
}); | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.removeFilter = function (filterKey) { | ||
var _this$filters = this.filters, | ||
del = _this$filters[filterKey], | ||
rest = _objectWithoutPropertiesLoose(_this$filters, [filterKey].map(_toPropertyKey)); | ||
this.filters = rest; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.enableEmptyQuery = function () { | ||
this.emptyQuery = true; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.disableEmptyQuery = function () { | ||
this.emptyQuery = false; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.registerClick = function (clickPosition, isSuggestion) { | ||
if (Number.isNaN(parseInt(clickPosition, 10))) { | ||
throw new Error('appbase-analytics: click position must be an integer.'); | ||
metrics._request('conversion', requestBody, callback); | ||
} | ||
}; // Sets the userID | ||
var commonHeaders = this._recordEventHeaders(); | ||
return fetch(this.url + "/" + this.index + "/_analytics", { | ||
method: 'POST', | ||
headers: _extends({}, commonHeaders, {}, isSuggestion ? { | ||
'X-Search-Suggestions-Click': true, | ||
'X-Search-Suggestions-ClickPosition': clickPosition | ||
} : { | ||
'X-Search-Click': true, | ||
'X-Search-ClickPosition': clickPosition | ||
}) | ||
}); | ||
}; | ||
metrics.setUserID = function (userID) { | ||
metrics.userID = userID; | ||
}; // Sets the global events | ||
AppbaseAnalytics.prototype.registerConversion = function () { | ||
var commonHeaders = this._recordEventHeaders(); | ||
return fetch(this.url + "/" + this.index + "/_analytics", { | ||
method: 'POST', | ||
headers: _extends({}, commonHeaders, { | ||
'X-Search-Conversion': true | ||
}) | ||
}); | ||
}; // Headers value will be based on the analytics current state, may or may not present | ||
metrics.setGlobalEventData = function (globalEvents) { | ||
metrics.globalEventData = globalEvents; | ||
}; // Sets the headers | ||
AppbaseAnalytics.prototype.getAnalyticsHeaders = function () { | ||
return _extends({}, this.searchQuery || this.emptyQuery ? { | ||
'X-Search-Query': this.searchQuery || '' | ||
} : null, {}, this.searchID ? { | ||
'X-Search-Id': this.searchID | ||
} : null, {}, this.searchState ? { | ||
'X-Search-State': JSON.stringify(this.searchState) | ||
} : null, {}, this.userID ? { | ||
'X-User-Id': this.userID | ||
} : null, {}, this.customEvents ? { | ||
'X-Search-CustomEvent': parseHeaders(this.customEvents) | ||
} : null, {}, this.filters ? { | ||
'X-Search-Filters': parseHeaders(this.filters) | ||
} : null); | ||
metrics.setHeaders = function (headers) { | ||
metrics.headers = headers; | ||
}; | ||
AppbaseAnalytics.prototype._recordEventHeaders = function () { | ||
if (!this.index) { | ||
throw new Error('appbase-analytics: A valid index must be present to record an event.'); | ||
} | ||
return metrics; | ||
} | ||
if (!this.credentials) { | ||
throw new Error('appbase-analytics: Auth credentials is missing.'); | ||
} | ||
var index = { | ||
init: initClient | ||
}; | ||
if (!this.searchID) { | ||
throw new Error('appbase-analytics: searchID must be present to record an event.'); | ||
} | ||
return _extends({}, this.headers, { | ||
'Content-Type': 'application/json', | ||
Authorization: "Basic " + btoa(this.credentials), | ||
'X-Search-Id': this.searchID | ||
}, this.userID ? { | ||
'X-User-Id': this.userID | ||
} : null, {}, this.customEvents ? { | ||
'X-Search-CustomEvent': parseHeaders(this.customEvents) | ||
} : null); | ||
}; | ||
return client; | ||
} | ||
export default index; |
@@ -25,58 +25,3 @@ (function (global, factory) { | ||
function _objectWithoutPropertiesLoose(source, excluded) { | ||
if (source == null) return {}; | ||
var target = {}; | ||
var sourceKeys = Object.keys(source); | ||
var key, i; | ||
for (i = 0; i < sourceKeys.length; i++) { | ||
key = sourceKeys[i]; | ||
if (excluded.indexOf(key) >= 0) continue; | ||
target[key] = source[key]; | ||
} | ||
return target; | ||
} | ||
function _toPrimitive(input, hint) { | ||
if (typeof input !== "object" || input === null) return input; | ||
var prim = input[Symbol.toPrimitive]; | ||
if (prim !== undefined) { | ||
var res = prim.call(input, hint || "default"); | ||
if (typeof res !== "object") return res; | ||
throw new TypeError("@@toPrimitive must return a primitive value."); | ||
} | ||
return (hint === "string" ? String : Number)(input); | ||
} | ||
function _toPropertyKey(arg) { | ||
var key = _toPrimitive(arg, "string"); | ||
return typeof key === "symbol" ? key : String(key); | ||
} | ||
/** | ||
* Function to parse the headers to a string | ||
*/ | ||
function parseHeaders(headers) { | ||
var finalStr = ''; | ||
if (headers) { | ||
Object.keys(headers).forEach(function (key, index) { | ||
finalStr += key + "=" + headers[key]; | ||
if (index < Object.keys(headers).length - 1) { | ||
finalStr += ','; | ||
} | ||
}); | ||
} | ||
return finalStr; | ||
} // Function to parse the URL | ||
function getURL(url) { | ||
return url && url.trim() !== '' ? url : 'https://scalr.api.appbase.io'; | ||
} | ||
// Function to parse the URL | ||
function btoa(input) { | ||
@@ -664,22 +609,34 @@ if (input === void 0) { | ||
function AppbaseAnalytics(config) { | ||
if (config === void 0) { | ||
config = {}; | ||
function validateIndex(index) { | ||
if (!index) { | ||
throw new Error('appbase-analytics: A valid index must be present to record analytics events.'); | ||
} | ||
this.index = config.index; | ||
this.credentials = config.credentials; | ||
this.url = getURL(config.url); | ||
this.userID = config.userID; | ||
this.customEvents = config.customEvents; | ||
this.searchQuery = undefined; | ||
this.searchID = undefined; | ||
this.searchState = null; | ||
this.filters = null; | ||
this.emptyQuery = config.emptyQuery !== undefined ? config.emptyQuery : true; // custom headers | ||
this.headers = null; | ||
} | ||
function validateCredentials(credentials) { | ||
if (!credentials) { | ||
throw new Error('appbase-analytics: Auth credentials is missing.'); | ||
} | ||
} | ||
function validateURL(url) { | ||
if (!url) { | ||
throw new Error('appbase-analytics: URL is missing.'); | ||
} | ||
} | ||
function validateQuery(query, queryID) { | ||
if ((query === undefined || query === null) && !queryID) { | ||
throw new Error('appbase-analytics: query or queryID must be present to register a click/conversion event'); | ||
} | ||
} | ||
function validateClickObjects(objects) { | ||
if (!objects || Object.keys(objects).length < 1) { | ||
throw new Error('appbase-analytics: at least one click object must be present to register a click event'); | ||
} | ||
} | ||
function validateConversionObjects(objects) { | ||
if (!objects || Object.keys(objects).length < 1) { | ||
throw new Error('appbase-analytics: at least one click object must be present to register a click event'); | ||
} | ||
} | ||
function index (config) { | ||
function initClient(config) { | ||
if (config === void 0) { | ||
@@ -689,200 +646,129 @@ config = {}; | ||
var client = new AppbaseAnalytics(config); | ||
AppbaseAnalytics.prototype.setIndex = function (index) { | ||
this.index = index; | ||
return this; | ||
var metrics = { | ||
credentials: config.credentials, | ||
index: config.index, | ||
url: config.url, | ||
userID: config.userID, | ||
globalEventData: config.globalEventData, | ||
queryID: '', | ||
headers: null | ||
}; | ||
validateIndex(metrics.index); | ||
validateCredentials(metrics.credentials); | ||
validateURL(metrics.url); | ||
AppbaseAnalytics.prototype.setCredentials = function (credentials) { | ||
this.credentials = credentials; | ||
return this; | ||
}; | ||
metrics._request = function (url, body, callback) { | ||
return browserPonyfill(metrics.url + "/" + metrics.index + "/_analytics/" + url, { | ||
method: 'PUT', | ||
headers: _extends({}, metrics.headers, { | ||
'Content-Type': 'application/json', | ||
Authorization: "Basic " + btoa(metrics.credentials) | ||
}), | ||
body: JSON.stringify(body) | ||
}).then(function (response) { | ||
if (callback) { | ||
callback(null, response); | ||
} | ||
})["catch"](function (err) { | ||
console.error(err); | ||
AppbaseAnalytics.prototype.setURL = function (url) { | ||
this.url = getURL(url); | ||
return this; | ||
}; | ||
if (callback) { | ||
callback(err, null); | ||
} | ||
}); | ||
}; // To register a search | ||
AppbaseAnalytics.prototype.setHeaders = function (headers) { | ||
this.headers = headers; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.setSearchQuery = function (searchQuery) { | ||
this.searchQuery = searchQuery; | ||
return this; | ||
}; | ||
metrics.search = function (searchConfig, callback) { | ||
validateQuery(searchConfig.query); | ||
AppbaseAnalytics.prototype.clearSearchQuery = function () { | ||
this.searchQuery = undefined; | ||
return this; | ||
}; | ||
var captureQueryID = function captureQueryID(err, res) { | ||
if (res) { | ||
res.json().then(function (response) { | ||
if (response && response.query_id) { | ||
metrics.queryID = response.query_id; | ||
} | ||
})["catch"](function (error) { | ||
console.error(error); | ||
}); | ||
} | ||
AppbaseAnalytics.prototype.setSearchID = function (searchID) { | ||
this.searchID = searchID; | ||
return this; | ||
}; | ||
if (callback) { | ||
callback(err, res); | ||
} | ||
}; // just to avoid the flow type error | ||
AppbaseAnalytics.prototype.clearSearchID = function () { | ||
this.searchID = undefined; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.setSearchState = function (searchState) { | ||
this.searchState = searchState; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
query: searchConfig.query, | ||
event_data: searchConfig.eventData, | ||
filters: searchConfig.filters, | ||
hits: searchConfig.hits, | ||
user_id: searchConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.clearSearchState = function () { | ||
this.searchState = null; | ||
return this; | ||
}; | ||
metrics._request('search', requestBody, captureQueryID); | ||
} | ||
}; // To register a click | ||
AppbaseAnalytics.prototype.setUserID = function (userID) { | ||
this.userID = userID; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.clearUserID = function () { | ||
this.userID = null; | ||
return this; | ||
}; | ||
metrics.click = function (clickConfig, callback) { | ||
validateQuery(clickConfig.query, clickConfig.queryID); | ||
validateClickObjects(clickConfig.objects); // just to avoid the flow type error | ||
AppbaseAnalytics.prototype.setCustomEvents = function (customEvents) { | ||
this.customEvents = customEvents; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
click_on: clickConfig.objects, | ||
click_type: clickConfig.type || 'result', | ||
query: clickConfig.query, | ||
query_id: clickConfig.queryID, | ||
event_data: clickConfig.eventData, | ||
user_id: clickConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.clearCustomEvents = function () { | ||
this.customEvents = null; | ||
return this; | ||
}; | ||
metrics._request('click', requestBody, callback); | ||
} | ||
}; // To register a conversion | ||
AppbaseAnalytics.prototype.addCustomEvent = function (customEvent) { | ||
this.customEvents = _extends({}, this.customEvents, { | ||
customEvent: customEvent | ||
}); | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.removeCustomEvent = function (eventKey) { | ||
var _this$customEvents = this.customEvents, | ||
del = _this$customEvents[eventKey], | ||
rest = _objectWithoutPropertiesLoose(_this$customEvents, [eventKey].map(_toPropertyKey)); | ||
metrics.conversion = function (conversionConfig, callback) { | ||
validateQuery(conversionConfig.query, conversionConfig.queryID); | ||
validateConversionObjects(conversionConfig.objects); // just to avoid the flow type error | ||
this.customEvents = rest; | ||
return this; | ||
}; | ||
if (metrics._request) { | ||
var requestBody = { | ||
conversion_on: conversionConfig.objects, | ||
query: conversionConfig.query, | ||
query_id: conversionConfig.queryID, | ||
event_data: conversionConfig.eventData, | ||
user_id: conversionConfig.userID | ||
}; | ||
AppbaseAnalytics.prototype.setFilters = function (filters) { | ||
this.filters = filters; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.clearFilters = function () { | ||
this.filters = null; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.addFilter = function (filter) { | ||
this.filters = _extends({}, this.filters, { | ||
filter: filter | ||
}); | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.removeFilter = function (filterKey) { | ||
var _this$filters = this.filters, | ||
del = _this$filters[filterKey], | ||
rest = _objectWithoutPropertiesLoose(_this$filters, [filterKey].map(_toPropertyKey)); | ||
this.filters = rest; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.enableEmptyQuery = function () { | ||
this.emptyQuery = true; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.disableEmptyQuery = function () { | ||
this.emptyQuery = false; | ||
return this; | ||
}; | ||
AppbaseAnalytics.prototype.registerClick = function (clickPosition, isSuggestion) { | ||
if (Number.isNaN(parseInt(clickPosition, 10))) { | ||
throw new Error('appbase-analytics: click position must be an integer.'); | ||
metrics._request('conversion', requestBody, callback); | ||
} | ||
}; // Sets the userID | ||
var commonHeaders = this._recordEventHeaders(); | ||
return browserPonyfill(this.url + "/" + this.index + "/_analytics", { | ||
method: 'POST', | ||
headers: _extends({}, commonHeaders, {}, isSuggestion ? { | ||
'X-Search-Suggestions-Click': true, | ||
'X-Search-Suggestions-ClickPosition': clickPosition | ||
} : { | ||
'X-Search-Click': true, | ||
'X-Search-ClickPosition': clickPosition | ||
}) | ||
}); | ||
}; | ||
metrics.setUserID = function (userID) { | ||
metrics.userID = userID; | ||
}; // Sets the global events | ||
AppbaseAnalytics.prototype.registerConversion = function () { | ||
var commonHeaders = this._recordEventHeaders(); | ||
return browserPonyfill(this.url + "/" + this.index + "/_analytics", { | ||
method: 'POST', | ||
headers: _extends({}, commonHeaders, { | ||
'X-Search-Conversion': true | ||
}) | ||
}); | ||
}; // Headers value will be based on the analytics current state, may or may not present | ||
metrics.setGlobalEventData = function (globalEvents) { | ||
metrics.globalEventData = globalEvents; | ||
}; // Sets the headers | ||
AppbaseAnalytics.prototype.getAnalyticsHeaders = function () { | ||
return _extends({}, this.searchQuery || this.emptyQuery ? { | ||
'X-Search-Query': this.searchQuery || '' | ||
} : null, {}, this.searchID ? { | ||
'X-Search-Id': this.searchID | ||
} : null, {}, this.searchState ? { | ||
'X-Search-State': JSON.stringify(this.searchState) | ||
} : null, {}, this.userID ? { | ||
'X-User-Id': this.userID | ||
} : null, {}, this.customEvents ? { | ||
'X-Search-CustomEvent': parseHeaders(this.customEvents) | ||
} : null, {}, this.filters ? { | ||
'X-Search-Filters': parseHeaders(this.filters) | ||
} : null); | ||
metrics.setHeaders = function (headers) { | ||
metrics.headers = headers; | ||
}; | ||
AppbaseAnalytics.prototype._recordEventHeaders = function () { | ||
if (!this.index) { | ||
throw new Error('appbase-analytics: A valid index must be present to record an event.'); | ||
} | ||
return metrics; | ||
} | ||
if (!this.credentials) { | ||
throw new Error('appbase-analytics: Auth credentials is missing.'); | ||
} | ||
var index = { | ||
init: initClient | ||
}; | ||
if (!this.searchID) { | ||
throw new Error('appbase-analytics: searchID must be present to record an event.'); | ||
} | ||
return _extends({}, this.headers, { | ||
'Content-Type': 'application/json', | ||
Authorization: "Basic " + btoa(this.credentials), | ||
'X-Search-Id': this.searchID | ||
}, this.userID ? { | ||
'X-User-Id': this.userID | ||
} : null, {}, this.customEvents ? { | ||
'X-Search-CustomEvent': parseHeaders(this.customEvents) | ||
} : null); | ||
}; | ||
return client; | ||
} | ||
return index; | ||
@@ -889,0 +775,0 @@ |
@@ -1,2 +0,2 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).aa=e()}(this,(function(){"use strict";function t(){return(t=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function e(t,e){if(null==t)return{};var r,n,o={},i=Object.keys(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||(o[r]=t[r]);return o}function r(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function n(t){var e="";return t&&Object.keys(t).forEach((function(r,n){e+=r+"="+t[r],n<Object.keys(t).length-1&&(e+=",")})),e}function o(t){return t&&""!==t.trim()?t:"https://scalr.api.appbase.io"}function i(t){void 0===t&&(t="");for(var e,r=t,n="",o=0,i=0,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.charAt(0|i)||(s="=",i%1);n+=s.charAt(63&o>>8-i%1*8)){if((e=r.charCodeAt(i+=.75))>255)throw new Error('"btoa" failed: The string to be encoded contains characters outside of the Latin1 range.');o=o<<8|e}return n}var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var a=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t,e){var r=function(t){function e(){this.fetch=!1,this.DOMException=t.DOMException}return e.prototype=t,new e}("undefined"!=typeof self?self:s);!function(t){!function(e){var r={searchParams:"URLSearchParams"in t,iterable:"Symbol"in t&&"iterator"in Symbol,blob:"FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in t,arrayBuffer:"ArrayBuffer"in t};if(r.arrayBuffer)var n=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],o=ArrayBuffer.isView||function(t){return t&&n.indexOf(Object.prototype.toString.call(t))>-1};function i(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function s(t){return"string"!=typeof t&&(t=String(t)),t}function a(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return r.iterable&&(e[Symbol.iterator]=function(){return e}),e}function u(t){this.map={},t instanceof u?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function h(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function c(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function f(t){var e=new FileReader,r=c(e);return e.readAsArrayBuffer(t),r}function p(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function l(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:r.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:r.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():r.arrayBuffer&&r.blob&&((e=t)&&DataView.prototype.isPrototypeOf(e))?(this._bodyArrayBuffer=p(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||o(t))?this._bodyArrayBuffer=p(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var t=h(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(f)}),this.text=function(){var t,e,r,n=h(this);if(n)return n;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,r=c(e),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}u.prototype.append=function(t,e){t=i(t),e=s(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},u.prototype.delete=function(t){delete this.map[i(t)]},u.prototype.get=function(t){return t=i(t),this.has(t)?this.map[t]:null},u.prototype.has=function(t){return this.map.hasOwnProperty(i(t))},u.prototype.set=function(t,e){this.map[i(t)]=s(e)},u.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},u.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),a(t)},u.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),a(t)},u.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),a(t)},r.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);var d=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function y(t,e){var r,n,o=(e=e||{}).body;if(t instanceof y){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new u(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,o||null==t._bodyInit||(o=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new u(e.headers)),this.method=(r=e.method||this.method||"GET",n=r.toUpperCase(),d.indexOf(n)>-1?n:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function b(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(n),decodeURIComponent(o))}})),e}function m(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new u(e.headers),this.url=e.url||"",this._initBody(t)}y.prototype.clone=function(){return new y(this,{body:this._bodyInit})},l.call(y.prototype),l.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},m.error=function(){var t=new m(null,{status:0,statusText:""});return t.type="error",t};var v=[301,302,303,307,308];m.redirect=function(t,e){if(-1===v.indexOf(e))throw new RangeError("Invalid status code");return new m(null,{status:e,headers:{location:t}})},e.DOMException=t.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function E(t,n){return new Promise((function(o,i){var s=new y(t,n);if(s.signal&&s.signal.aborted)return i(new e.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function h(){a.abort()}a.onload=function(){var t,e,r={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new u,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var r=t.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();e.append(n,o)}})),e)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var n="response"in a?a.response:a.responseText;o(new m(n,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new e.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&r.blob&&(a.responseType="blob"),s.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),s.signal&&(s.signal.addEventListener("abort",h),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",h)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}E.polyfill=!0,t.fetch||(t.fetch=E,t.Headers=u,t.Request=y,t.Response=m),e.Headers=u,e.Request=y,e.Response=m,e.fetch=E}({})}(r),delete r.fetch.polyfill,(e=r.fetch).default=r.fetch,e.fetch=r.fetch,e.Headers=r.Headers,e.Request=r.Request,e.Response=r.Response,t.exports=e}));a.fetch,a.Headers,a.Request,a.Response;function u(t){void 0===t&&(t={}),this.index=t.index,this.credentials=t.credentials,this.url=o(t.url),this.userID=t.userID,this.customEvents=t.customEvents,this.searchQuery=void 0,this.searchID=void 0,this.searchState=null,this.filters=null,this.emptyQuery=void 0===t.emptyQuery||t.emptyQuery,this.headers=null}return function(s){void 0===s&&(s={});var h=new u(s);return u.prototype.setIndex=function(t){return this.index=t,this},u.prototype.setCredentials=function(t){return this.credentials=t,this},u.prototype.setURL=function(t){return this.url=o(t),this},u.prototype.setHeaders=function(t){return this.headers=t,this},u.prototype.setSearchQuery=function(t){return this.searchQuery=t,this},u.prototype.clearSearchQuery=function(){return this.searchQuery=void 0,this},u.prototype.setSearchID=function(t){return this.searchID=t,this},u.prototype.clearSearchID=function(){return this.searchID=void 0,this},u.prototype.setSearchState=function(t){return this.searchState=t,this},u.prototype.clearSearchState=function(){return this.searchState=null,this},u.prototype.setUserID=function(t){return this.userID=t,this},u.prototype.clearUserID=function(){return this.userID=null,this},u.prototype.setCustomEvents=function(t){return this.customEvents=t,this},u.prototype.clearCustomEvents=function(){return this.customEvents=null,this},u.prototype.addCustomEvent=function(e){return this.customEvents=t({},this.customEvents,{customEvent:e}),this},u.prototype.removeCustomEvent=function(t){var n=this.customEvents,o=(n[t],e(n,[t].map(r)));return this.customEvents=o,this},u.prototype.setFilters=function(t){return this.filters=t,this},u.prototype.clearFilters=function(){return this.filters=null,this},u.prototype.addFilter=function(e){return this.filters=t({},this.filters,{filter:e}),this},u.prototype.removeFilter=function(t){var n=this.filters,o=(n[t],e(n,[t].map(r)));return this.filters=o,this},u.prototype.enableEmptyQuery=function(){return this.emptyQuery=!0,this},u.prototype.disableEmptyQuery=function(){return this.emptyQuery=!1,this},u.prototype.registerClick=function(e,r){if(Number.isNaN(parseInt(e,10)))throw new Error("appbase-analytics: click position must be an integer.");var n=this._recordEventHeaders();return a(this.url+"/"+this.index+"/_analytics",{method:"POST",headers:t({},n,{},r?{"X-Search-Suggestions-Click":!0,"X-Search-Suggestions-ClickPosition":e}:{"X-Search-Click":!0,"X-Search-ClickPosition":e})})},u.prototype.registerConversion=function(){var e=this._recordEventHeaders();return a(this.url+"/"+this.index+"/_analytics",{method:"POST",headers:t({},e,{"X-Search-Conversion":!0})})},u.prototype.getAnalyticsHeaders=function(){return t({},this.searchQuery||this.emptyQuery?{"X-Search-Query":this.searchQuery||""}:null,{},this.searchID?{"X-Search-Id":this.searchID}:null,{},this.searchState?{"X-Search-State":JSON.stringify(this.searchState)}:null,{},this.userID?{"X-User-Id":this.userID}:null,{},this.customEvents?{"X-Search-CustomEvent":n(this.customEvents)}:null,{},this.filters?{"X-Search-Filters":n(this.filters)}:null)},u.prototype._recordEventHeaders=function(){if(!this.index)throw new Error("appbase-analytics: A valid index must be present to record an event.");if(!this.credentials)throw new Error("appbase-analytics: Auth credentials is missing.");if(!this.searchID)throw new Error("appbase-analytics: searchID must be present to record an event.");return t({},this.headers,{"Content-Type":"application/json",Authorization:"Basic "+i(this.credentials),"X-Search-Id":this.searchID},this.userID?{"X-User-Id":this.userID}:null,{},this.customEvents?{"X-Search-CustomEvent":n(this.customEvents)}:null)},h}})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).aa=t()}(this,(function(){"use strict";function e(){return(e=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function t(e){void 0===e&&(e="");for(var t,r=e,n="",o=0,i=0,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.charAt(0|i)||(s="=",i%1);n+=s.charAt(63&o>>8-i%1*8)){if((t=r.charCodeAt(i+=.75))>255)throw new Error('"btoa" failed: The string to be encoded contains characters outside of the Latin1 range.');o=o<<8|t}return n}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var n=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e,t){var n=function(e){function t(){this.fetch=!1,this.DOMException=e.DOMException}return t.prototype=e,new t}("undefined"!=typeof self?self:r);!function(e){!function(t){var r={searchParams:"URLSearchParams"in e,iterable:"Symbol"in e&&"iterator"in Symbol,blob:"FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in e,arrayBuffer:"ArrayBuffer"in e};if(r.arrayBuffer)var n=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],o=ArrayBuffer.isView||function(e){return e&&n.indexOf(Object.prototype.toString.call(e))>-1};function i(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function s(e){return"string"!=typeof e&&(e=String(e)),e}function a(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return r.iterable&&(t[Symbol.iterator]=function(){return t}),t}function u(e){this.map={},e instanceof u?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function c(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function f(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function h(e){var t=new FileReader,r=f(t);return t.readAsArrayBuffer(e),r}function d(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function l(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:r.blob&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:r.formData&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():r.arrayBuffer&&r.blob&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=d(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||o(e))?this._bodyArrayBuffer=d(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},r.blob&&(this.blob=function(){var e=c(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?c(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(h)}),this.text=function(){var e,t,r,n=c(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=f(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n<t.length;n++)r[n]=String.fromCharCode(t[n]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r.formData&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}u.prototype.append=function(e,t){e=i(e),t=s(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},u.prototype.delete=function(e){delete this.map[i(e)]},u.prototype.get=function(e){return e=i(e),this.has(e)?this.map[e]:null},u.prototype.has=function(e){return this.map.hasOwnProperty(i(e))},u.prototype.set=function(e,t){this.map[i(e)]=s(t)},u.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},u.prototype.keys=function(){var e=[];return this.forEach((function(t,r){e.push(r)})),a(e)},u.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),a(e)},u.prototype.entries=function(){var e=[];return this.forEach((function(t,r){e.push([r,t])})),a(e)},r.iterable&&(u.prototype[Symbol.iterator]=u.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function p(e,t){var r,n,o=(t=t||{}).body;if(e instanceof p){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new u(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,o||null==e._bodyInit||(o=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new u(t.headers)),this.method=(r=t.method||this.method||"GET",n=r.toUpperCase(),y.indexOf(n)>-1?n:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(o))}})),t}function m(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new u(t.headers),this.url=t.url||"",this._initBody(e)}p.prototype.clone=function(){return new p(this,{body:this._bodyInit})},l.call(p.prototype),l.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new u(this.headers),url:this.url})},m.error=function(){var e=new m(null,{status:0,statusText:""});return e.type="error",e};var w=[301,302,303,307,308];m.redirect=function(e,t){if(-1===w.indexOf(t))throw new RangeError("Invalid status code");return new m(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function v(e,n){return new Promise((function(o,i){var s=new p(e,n);if(s.signal&&s.signal.aborted)return i(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function c(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new u,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();t.append(n,o)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var n="response"in a?a.response:a.responseText;o(new m(n,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&r.blob&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",c),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",c)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}v.polyfill=!0,e.fetch||(e.fetch=v,e.Headers=u,e.Request=p,e.Response=m),t.Headers=u,t.Request=p,t.Response=m,t.fetch=v}({})}(n),delete n.fetch.polyfill,(t=n.fetch).default=n.fetch,t.fetch=n.fetch,t.Headers=n.Headers,t.Request=n.Request,t.Response=n.Response,e.exports=t}));n.fetch,n.Headers,n.Request,n.Response;function o(e,t){if(null==e&&!t)throw new Error("appbase-analytics: query or queryID must be present to register a click/conversion event")}return{init:function(r){void 0===r&&(r={});var i={credentials:r.credentials,index:r.index,url:r.url,userID:r.userID,globalEventData:r.globalEventData,queryID:"",headers:null};return function(e){if(!e)throw new Error("appbase-analytics: A valid index must be present to record analytics events.")}(i.index),function(e){if(!e)throw new Error("appbase-analytics: Auth credentials is missing.")}(i.credentials),function(e){if(!e)throw new Error("appbase-analytics: URL is missing.")}(i.url),i._request=function(r,o,s){return n(i.url+"/"+i.index+"/_analytics/"+r,{method:"PUT",headers:e({},i.headers,{"Content-Type":"application/json",Authorization:"Basic "+t(i.credentials)}),body:JSON.stringify(o)}).then((function(e){s&&s(null,e)})).catch((function(e){console.error(e),s&&s(e,null)}))},i.search=function(e,t){o(e.query);if(i._request){var r={query:e.query,event_data:e.eventData,filters:e.filters,hits:e.hits,user_id:e.userID};i._request("search",r,(function(e,r){r&&r.json().then((function(e){e&&e.query_id&&(i.queryID=e.query_id)})).catch((function(e){console.error(e)})),t&&t(e,r)}))}},i.click=function(e,t){if(o(e.query,e.queryID),function(e){if(!e||Object.keys(e).length<1)throw new Error("appbase-analytics: at least one click object must be present to register a click event")}(e.objects),i._request){var r={click_on:e.objects,click_type:e.type||"result",query:e.query,query_id:e.queryID,event_data:e.eventData,user_id:e.userID};i._request("click",r,t)}},i.conversion=function(e,t){if(o(e.query,e.queryID),function(e){if(!e||Object.keys(e).length<1)throw new Error("appbase-analytics: at least one click object must be present to register a click event")}(e.objects),i._request){var r={conversion_on:e.objects,query:e.query,query_id:e.queryID,event_data:e.eventData,user_id:e.userID};i._request("conversion",r,t)}},i.setUserID=function(e){i.userID=e},i.setGlobalEventData=function(e){i.globalEventData=e},i.setHeaders=function(e){i.headers=e},i}}})); | ||
//# sourceMappingURL=analytics.umd.min.js.map |
{ | ||
"name": "@appbaseio/analytics", | ||
"version": "1.0.0-alpha.1", | ||
"version": "2.0.0-beta", | ||
"description": "Universal analytics library for appbase.io apps", | ||
@@ -20,3 +20,3 @@ "main": "src/index.js", | ||
"type": "git", | ||
"url": "git+https://github.com/appbaseio/appbase-analytics.git" | ||
"url": "git+https://github.com/appbaseio/analytics.git" | ||
}, | ||
@@ -26,5 +26,5 @@ "author": "bietkul <kuldepsaxena155@gmail.com>", | ||
"bugs": { | ||
"url": "https://github.com/appbaseio/appbase-analytics/issues" | ||
"url": "https://github.com/appbaseio/analytics/issues" | ||
}, | ||
"homepage": "https://github.com/appbaseio/appbase-analytics#readme", | ||
"homepage": "https://github.com/appbaseio/analytics#readme", | ||
"lint-staged": { | ||
@@ -31,0 +31,0 @@ "*.js": [ |
474
README.md
@@ -0,1 +1,475 @@ | ||
[![NPM Version](https://img.shields.io/npm/v/@appbaseio/analytics.svg?style=flat)](https://www.npmjs.com/package/@appbaseio/analytics) | ||
### Appbase Analytics | ||
A universal analytics library that allows you to register click, conversion and custom events for appbase.io apps. | ||
## TOC | ||
- [Getting started](#getting-started) | ||
- [Browser](#browser) | ||
- [Node.js](#nodejs) | ||
- [Use cases](#use-cases) | ||
- [Initialize search](#initialize-search) | ||
- [Register click events](#register-click-events) | ||
- [Register conversions](#register-conversions) | ||
- [Set user](#set-user) | ||
- [Set custom events](#set-custom-events) | ||
- [Set search state](#set-search-state) | ||
- [API Reference](#api-reference) | ||
- [Contributing](#contributing) | ||
- [Other Projects You Might Like](#other-projects-you-might-like) | ||
- [License](#license) | ||
## Getting started | ||
### Browser | ||
#### 1. Load the library | ||
The analytics library can be either loaded via [jsDelivr CDN](https://www.jsdelivr.com/) or directly bundled with your application. | ||
You can use the UMD build in browsers by following the below snippet: | ||
<!-- prettier-ignore-start --> | ||
```html | ||
<script defer src="https://cdn.jsdelivr.net/npm/@appbaseio/analytics@1.0.0-alpha.1/dist/@appbaseio/analytics.umd.min.js" | ||
></script> | ||
``` | ||
<!-- prettier-ignore-end --> | ||
#### 2. Initialization | ||
```js | ||
const aaInstance = aa({ | ||
index: 'APP_NAME', | ||
credentials: 'APP_CREDENTIALS' | ||
}); | ||
``` | ||
### Node.js | ||
#### 1. Install the library | ||
Install the library by following the below command: | ||
```bash | ||
npm install @appbaseio/analytics | ||
# or | ||
yarn add @appbaseio/analytics | ||
``` | ||
#### 2. Initialization | ||
```js | ||
const aa = require('@appbaseio/analytics'); | ||
const aaInstance = aa({ | ||
index: 'APP_NAME', | ||
credentials: 'APP_CREDENTIALS' | ||
}); | ||
``` | ||
[⬆ Back to Top](#appbase-analytics) | ||
## Use cases | ||
The analytics library provides the utility methods to implement the appbase.io search analytics, the common use-cases are to record the clicks, conversions and apply the search headers to create a search session. | ||
### Initialize search | ||
To register the click events you just need to create a search session and get the search id, a search session can be initialized bypassing the `x-search-query` header in the `_msearch` or `_search` request. | ||
We recommend to use `getAnalyticsHeaders` method to attach the analytics headers in search requests. For example: | ||
```js | ||
const aa = require('@appbaseio/analytics'); | ||
const aaInstance = aa({ | ||
index: 'APP_NAME', | ||
credentials: 'APP_CREDENTIALS' | ||
}); | ||
const analyticsHeaders = aaInstance | ||
.setSearchQuery('harry') | ||
.getAnalyticsHeaders(); | ||
fetch(`https://scalr.api.appbse.io/${APP_NAME}/_search`, { | ||
headers: analyticsHeaders | ||
}) | ||
.then(res => { | ||
const searchID = res.headers.get('X-Search-Id'); | ||
// Set the search id back to the analytics instance | ||
if (searchID) { | ||
aaInstance.setSearchID(searchID); | ||
} | ||
}) | ||
.catch(err => { | ||
console.error(err); | ||
}); | ||
``` | ||
Once you get the `searchID` back you need to use it to record the analytics events. | ||
### Register click events | ||
Click events can be registered with the help of `registerClick` method which has the following signature: | ||
```ts | ||
registerClick( | ||
clickPosition: number, // position of the item in the list | ||
isSuggestion?: boolean // whether a click is of type suggestion or results | ||
): Promise<any> | ||
``` | ||
#### Register a result click | ||
```js | ||
aa() | ||
.setIndex('APP_NAME') // If index is not set during initialization | ||
.setCredentials('APP_CREDENTIALS') // If credentials is not set during initialization | ||
.setSearchID('SEARCH_ID') // SEARCH_ID must be present otherwise the function will throw an error | ||
.registerClick(`CLICK_POSITION`); | ||
``` | ||
#### Register a suggestion click | ||
```js | ||
aa() | ||
.setIndex('APP_NAME') // If index is not set during initialization | ||
.setCredentials('APP_CREDENTIALS') // If credentials is not set during initialization | ||
.setSearchID('SEARCH_ID') // SEARCH_ID must be present otherwise the function will throw an error | ||
.registerClick(`CLICK_POSITION`, true); | ||
``` | ||
### Register conversions | ||
```js | ||
aa() | ||
.setIndex('APP_NAME') // If index is not set during initialization | ||
.setCredentials('APP_CREDENTIALS') // If credentials is not set during initialization | ||
.setSearchID('SEARCH_ID') // SEARCH_ID must be present otherwise the function will throw an error | ||
.registerConversion(); | ||
``` | ||
### Set user | ||
```js | ||
aa().setUserID('harry'); | ||
``` | ||
### Set custom events | ||
```js | ||
aa().setCustomEvents({ | ||
key1: 'value1', | ||
key2: 'value2' | ||
}); | ||
``` | ||
### Set search state | ||
```js | ||
aa().setSearchState({ | ||
BookSensor: { | ||
dataField: 'original_title', | ||
value: 'harry', | ||
queryFormat: 'or' | ||
} | ||
}); | ||
``` | ||
[⬆ Back to Top](#appbase-analytics) | ||
## API Reference | ||
### Initialization | ||
Although this library supports chaining i.e you can set and clear anything whenever you want but you can initialize it at once with some common properties to avoid the duplication. | ||
```js | ||
const aa = require('@appbaseio/analytics'); | ||
const aaInstance = aa({ | ||
index: 'APP_NAME', | ||
credentials: 'APP_CREDENTIALS' | ||
}); | ||
``` | ||
Optional configuration options: | ||
| Option | Type | Default | Description | | ||
| ----------------- | --------- | ------------------------------ | ----------------------------------------------------------------------------------- | | ||
| **`index`** | `string` | None (required) | App name for appbase.io apps or index name in case of `Arc` or `clusters`. | | ||
| **`credentials`** | `string` | None (required) | API key for appbase.io hosted application. | | ||
| `url` | `string` | `https://scalr.api.appbase.io` | Not needed for appbase.io apps but in case of `Arc` you need to define the arc URL. | | ||
| `userID` | `string` | null | Sets the userID to be recorded. | | ||
| `customEvents` | `object` | null | To set the custom events | | ||
| `headers` | `object` | null | To set the custom headers | | ||
| `emptyQuery` | `boolean` | true | To define whether to record the empty queries or not | | ||
### Methods | ||
## | ||
```ts | ||
setIndex(index: string) | ||
``` | ||
To set the index or app name. | ||
## | ||
```ts | ||
setCredentials(credentials: string) | ||
``` | ||
To set the application auth credentials. | ||
## | ||
```ts | ||
setURL(url: string) | ||
``` | ||
To set the URL, required when you use the appbase.io clusters or `Arc`. | ||
## | ||
```ts | ||
setHeaders(headers: Object) | ||
``` | ||
It allows you to set the custom headers in analytics endpoints. | ||
## | ||
```ts | ||
setSearchQuery(searchQuery: string) | ||
``` | ||
Sets the search query which is needed to retrieve the search headers. | ||
## | ||
```ts | ||
clearSearchQuery(); | ||
``` | ||
Clears the search query | ||
## | ||
```ts | ||
setSearchID(searchID: string) | ||
``` | ||
Sets the search ID which is required to register the analytics events. | ||
## | ||
```ts | ||
clearSearchID(); | ||
``` | ||
Clears the `searchID` | ||
## | ||
```ts | ||
setSearchState(searchState: string) | ||
``` | ||
Sets the search state which will be used to retrieve the search headers. | ||
## | ||
```ts | ||
clearSearchState(); | ||
``` | ||
Clears the saved search state. | ||
## | ||
```ts | ||
setUserID(userID: string) | ||
``` | ||
Sets the user ID which will be used to retrieve the search headers. | ||
## | ||
```ts | ||
clearUserID(); | ||
``` | ||
Clears the userID | ||
## | ||
```ts | ||
setCustomEvents(customEvents: Object) | ||
``` | ||
Sets the custom events which will override the existing custom events and will be used further in the analytics headers. | ||
For example: | ||
```js | ||
aa().setCustomEvents({ | ||
platform: 'mac', | ||
user_segment: 'free' | ||
}); | ||
``` | ||
## | ||
```ts | ||
clearCustomEvents(); | ||
``` | ||
Clears the existing custom events | ||
## | ||
```ts | ||
addCustomEvent(customEvent: Object) | ||
``` | ||
Add a particular custom event in the existing custom events. | ||
```js | ||
aa().addCustomEvent({ | ||
platform: 'mac' | ||
}); | ||
``` | ||
## | ||
```ts | ||
removeCustomEvent(eventKey: string) | ||
``` | ||
Remove a custom event by key | ||
```js | ||
aa().removeCustomEvent('platform'); | ||
``` | ||
## | ||
```ts | ||
setFilters(filters: Object) | ||
``` | ||
Set the filters which will be used to retrieve the search headers. | ||
```js | ||
aa().setFilters({ | ||
brand: 'Adidas', | ||
category: 'shoes' | ||
}); | ||
``` | ||
## | ||
```ts | ||
clearFilters(); | ||
``` | ||
Clear the filters | ||
## | ||
```ts | ||
addFilter(filter: Object) | ||
``` | ||
Adds a filter in the existing filters. | ||
## | ||
```ts | ||
removeFilter(filterKey: string) | ||
``` | ||
Removes a filter by key | ||
## | ||
```ts | ||
enableEmptyQuery(); | ||
``` | ||
Enables the recording of empty queries i.e create a search session even if the search query is empty. | ||
## | ||
```ts | ||
disableEmptyQuery(); | ||
``` | ||
Disables the recording of empty queries. | ||
## | ||
```ts | ||
registerClick( | ||
clickPosition: number, | ||
isSuggestion?: boolean | ||
): Promise<any> | ||
``` | ||
Registers a click event | ||
## | ||
```ts | ||
registerConversion(): Promise<any> | ||
``` | ||
Registers a search conversion | ||
## | ||
```ts | ||
getAnalyticsHeaders(): Object | ||
``` | ||
Returns a list of search headers based on the analytics state which needs to be applied to the `_search` & `_msearch` request to create a search session. | ||
[⬆ Back to Top](#appbase-analytics) | ||
## Contributing | ||
Fork the repo and run the following command to run & test locally. | ||
```bash | ||
yarn && yarn test | ||
``` | ||
## Other Projects You Might Like | ||
- [**Arc**](https://github.com/appbaseio/arc) API Gateway for ElasticSearch (Out of the box Security, Rate Limit Features, Record Analytics and Request Logs). | ||
- [**ReactiveSearch**](https://github.com/appbaseio/reactivesearch) ReactiveSearch is an Elasticsearch UI components library for React, React Native and Vue. It has 25+ components consisting of Lists, Ranges, Search UIs, Result displays and a way to bring any existing UI component into the library. | ||
- **searchbox** A lightweight and performance focused searchbox UI libraries to query and display results from your ElasticSearch app (aka index). | ||
- [**Vanilla**](https://github.com/appbaseio/searchbox) - (~16kB Minified + Gzipped) | ||
- [**React**](https://github.com/appbaseio/react-searchbox) - (~30kB Minified + Gzipped) | ||
- [**Vue**](https://github.com/appbaseio/vue-searchbox) - (~22kB Minified + Gzipped) | ||
- [**Dejavu**](https://github.com/appbaseio/dejavu) allows viewing raw data within an appbase.io (or Elasticsearch) app. **Soon to be released feature:** An ability to import custom data from CSV and JSON files, along with a guided walkthrough on applying data mappings. | ||
- [**Mirage**](https://github.com/appbaseio/mirage) ReactiveSearch components can be extended using custom Elasticsearch queries. For those new to Elasticsearch, Mirage provides an intuitive GUI for composing queries. | ||
- [**ReactiveMaps**](https://github.com/appbaseio/reactivesearch/tree/next/packages/maps) is a similar project to Reactive Search that allows building realtime maps easily. | ||
- [**appbase-js**](https://github.com/appbaseio/appbase-js) While building search UIs is dandy with Reactive Search, you might also need to add some input forms. **appbase-js** comes in handy there. | ||
## License | ||
This library is [Apache licensed](LICENSE.md). | ||
[⬆ Back to Top](#appbase-analytics) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Mixed license
License(Experimental) Package contains multiple licenses.
Found 1 instance in 1 package
155338
476
5
1
1039