UNPKG

@sitecore-jss/sitecore-jss

Version:

This module is provided as a part of Sitecore JavaScript Rendering SDK. It contains the core JSS APIs (layout service) and utilities.

59 lines (58 loc) 2.95 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.trackEvent = trackEvent; const utils_1 = require("./../utils"); /** * Note: fetch api needs to use `credentials: include` in order for Sitecore cookies to be included in CORS requests * which is necessary for analytics and such * @param {string} url url to fetch * @param {unknown[]} data data to send * @param {HttpDataFetcher<T>} fetcher data fetcher * @param {querystring.ParsedUrlQueryInput} params additional params to send */ function fetchData(url_1, data_1, fetcher_1) { return __awaiter(this, arguments, void 0, function* (url, data, fetcher, params = {}) { const requestData = Object.assign(Object.assign({}, (typeof data === 'object' && data !== null ? data : {})), { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, (typeof data === 'object' && data !== null && 'headers' in data ? data.headers : {})), body: JSON.stringify(data) }); return fetcher((0, utils_1.resolveUrl)(url, params), requestData).then((response) => { return response.data; }); }); } /** * Resolve tracking endpoint url * @param {TrackingRequestOptions} options options for the tracking service * @returns {string} tracking api url */ function resolveTrackingUrl(options) { const { host = '', serviceUrl = '/sitecore/api/jss/track', action = 'event' } = options; return `${host}${serviceUrl}/${action}`; } /** * Makes a request to Sitecore Layout Service for the specified route item path. * @param {Array<EventInstance | GoalInstance | OutcomeInstance | CampaignInstance | PageViewInstance>} events events to send * @param {TrackingRequestOptions} options options for the tracking service * @returns {Promise<void>} void */ function trackEvent(events, options) { const { querystringParams } = options; if (!options.test && (0, utils_1.isServer)()) { // do nothing for SSR, only track events when a browser requests it return Promise.resolve(); } if (!Array.isArray(events)) { events = [events]; } const fetchUrl = resolveTrackingUrl(options); return fetchData(fetchUrl, events, options.fetcher, querystringParams); }