UNPKG

@inyourarea/aard-client-js

Version:

A JavaScript tracking library for the Aard Platform at InYourArea.co.uk. Record and track activity across the different services of the platform.

88 lines 3.28 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import NodeFetch from 'node-fetch'; import { composeTransformers } from '../transformers'; import { retryAsync, createLogger } from '../helpers'; export var createClient = function (_a) { var baseUrl = _a.baseUrl, apiKey = _a.apiKey, fetchFn_ = _a.fetchFn, _b = _a.maxRetries, maxRetries = _b === void 0 ? 3 : _b, debug = _a.debug; if (!baseUrl) { throw new Error("BaseUrl is mandatory"); } if (!apiKey) { throw new Error("apiKey is mandatory"); } var fetchFn = NodeFetch; if (!fetchFn_) { if (typeof window !== 'undefined') { fetchFn = window.fetch; } } else { fetchFn = fetchFn_; } var logger = createLogger(!!debug); var requestHeaders = { 'Authorization': apiKey, }; logger('Aard client inizialized with:\n', "- api key " + apiKey + "\n", "- base url " + baseUrl + "\n", "- max retries " + maxRetries + "\n"); var transformEvent = function (event, transformers) { return composeTransformers.apply(void 0, transformers)(event); }; var saveFragment = function (dimensions) { return retryAsync(function () { return fetchFn(baseUrl + "/fragments", { method: 'POST', headers: __assign({}, requestHeaders, { 'Content-Type': 'application/json; charset=utf-8' }), body: JSON.stringify(dimensions), }) .then(function (response) { return response.json(); }) .then(function (_a) { var hash = _a.hash; return hash; }); }, maxRetries) .then(function (result) { logger("Fragment saved with hash " + result, dimensions); return result; }) .catch(function (error) { logger("ERROR: Failed to save Fragment", dimensions, error); }); }; var sendEvent = function (event) { return retryAsync(function () { return fetchFn(baseUrl + "/records", { method: 'POST', headers: __assign({}, requestHeaders, { 'Content-Type': 'application/json; charset=utf-8' }), body: JSON.stringify(event), }) .then(function (response) { return response.json(); }) .then(function (_a) { var accepted = _a.accepted; return accepted; }); }, maxRetries) .then(function (result) { logger("Event " + (result ? 'recorder' : 'not recorded'), event); return result; }) .catch(function (error) { logger("ERROR: Failed to send event", event, error); }); }; return { transformEvent: transformEvent, saveFragment: saveFragment, sendEvent: sendEvent, }; }; //# sourceMappingURL=client.js.map