### trackSessionStart Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-tracker.html Sends a session start event to the API. ```APIDOC ## trackSessionStart ### Description Sends a session start event to the API. ### Method Not specified (likely a client-side method call) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **networkParameters** (object) - Optional - Parameters relevant to the network request - **timeout** (number) - Optional - Request timeout (in milliseconds) ### Request Example ```javascript constructorio.tracker.trackSessionStart(); ``` ### Response #### Success Response (true) - Returns `true` on success. #### Error Response - Returns an `Error` object on failure. #### Response Example ``` true | Error ``` ``` -------------------------------- ### Track Session Start (V2) Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_tracker.js.html Sends a session start event using the V2 tracking endpoint. This method is intended for internal use and queues the request without immediate sending. ```javascript /** * Send session start event to API * @private * @function trackSessionStartV2 * @param {object} [networkParameters] - Parameters relevant to the network request * @param {number} [networkParameters.timeout] - Request timeout (in milliseconds) * @returns {(true|Error)} * @example * constructorio.tracker.trackSessionStartV2(); */ trackSessionStartV2(networkParameters = {}) { const url = `${this.options.serviceUrl}/v2/behavioral_action/session_start?`; this.requests.queue(`${url}${applyParamsAsString({}, this.options)}`, 'POST', undefined, networkParameters); this.requests.send(); return true; } ``` -------------------------------- ### Instantiate Client in DOM-less Environment Source: https://github.com/constructor-io/constructorio-client-javascript/wiki/Utilization-in-a-DOM-less-environment When using the client in a DOM-less environment, you must supply parameters like clientId, sessionId, and userId manually. This example shows the basic instantiation with these required parameters. ```javascript const instance = new ConstructorIO({ apiKey, clientId, sessionId, userId, sendTrackingEvents: true, }); ``` -------------------------------- ### Track Agent Result Load Started Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-tracker.html Log the initiation of the agent results page load. This event should be triggered before the results are fully displayed. ```javascript constructorio.tracker.trackAgentResultLoadStarted( { intent: 'show me a recipe for a cookie', intentResultId: 'Zde93fd-f955-4020-8b8d-6b21b93cb5a2', }, ); ``` -------------------------------- ### trackSessionStartV2 Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_tracker.js.html Sends a session start event to the API using the v2 behavioral endpoint. This method is intended for internal use. ```APIDOC ## trackSessionStartV2 ### Description Sends a session start event to the API using the v2 behavioral endpoint. This method is intended for internal use. ### Method POST ### Endpoint /v2/behavioral_action/session_start ### Parameters #### Query Parameters - **_dt** (number) - Required - Timestamp of the event. ### Request Example ```json { "example": "POST /v2/behavioral_action/session_start?key=YOUR_API_KEY&_dt=1678886400000" } ``` ### Response #### Success Response (200) Returns true if the request was queued successfully. #### Response Example ```json { "example": "true" } ``` ``` -------------------------------- ### Get Search Results Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-search.html Retrieve standard search results from the Constructor.io API. Use this for typical product searches with options to filter, sort, and paginate results. ```javascript constructorio.search.getSearchResults('t-shirt', { resultsPerPage: 40, filters: { size: 'medium' }, filterMatchTypes: { size: 'all' } }); ``` -------------------------------- ### Get Recommendations with Filters Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-recommendations.html Use this snippet to retrieve a specified number of recommendations for a given pod, with options to filter results by properties like size. ```javascript constructorio.recommendations.getRecommendations('t-shirt-best-sellers', { numResults: 5, filters: { size: 'medium' }, }); ``` -------------------------------- ### Track Session Start Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_tracker.js.html Sends a session start event to the standard tracking endpoint. This method queues the request and then triggers sending it via the request queue. ```javascript /** * Send session start event to API * * @function trackSessionStart * @param {object} [networkParameters] - Parameters relevant to the network request * @param {number} [networkParameters.timeout] - Request timeout (in milliseconds) * @returns {(true|Error)} * @example * constructorio.tracker.trackSessionStart(); */ trackSessionStart(networkParameters = {}) { const url = `${this.options.serviceUrl}/behavior?`; const queryParams = { action: 'session_start' }; this.requests.queue(`${url}${applyParamsAsString(queryParams, this.options)}`, undefined, undefined, networkParameters); this.requests.send(); return true; } ``` -------------------------------- ### Track Session Start Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-tracker.html Send a session start event to the API. This function can optionally accept network parameters such as a request timeout. ```javascript constructorio.tracker.trackSessionStart(); ``` -------------------------------- ### Track Assistant Result Load Started Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-tracker.html Call this when the results page for an assistant begins to load. This method is deprecated; use trackAgentResultLoadStarted instead. ```javascript constructorio.tracker.trackAssistantResultLoadStarted( { intent: 'show me a recipe for a cookie', intentResultId: 'Zde93fd-f955-4020-8b8d-6b21b93cb5a2', }, ); ``` -------------------------------- ### Get Quiz Results Configuration Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-quizzes.html Retrieve quiz results page configuration from the Constructor.io API. Pass the quiz ID and optional parameters like quiz version ID. ```javascript constructorio.quizzes.getQuizResultsConfig('quizId', { quizVersionId: '123' }); ``` -------------------------------- ### Get Recommendations Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_recommendations.js.html Use this snippet to retrieve recommendations for a specific pod. It allows for specifying the number of results and applying filters. Ensure the pod ID is valid and any filters are correctly formatted. ```javascript constructorio.recommendations.getRecommendations('t-shirt-best-sellers', { numResults: 5, filters: { size: 'medium' }, }); ``` -------------------------------- ### Get Autocomplete Results Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-autocomplete.html Retrieve autocomplete suggestions and results from the Constructor.io API. This method allows specifying the search query and optional parameters to refine the results, such as the number of results per section and filters. ```javascript constructorio.autocomplete.getAutocompleteResults('t-shirt', { resultsPerSection: { Products: 5, 'Search Suggestions': 10, }, filters: { size: 'medium' }, }); ``` -------------------------------- ### Get Browse Results with Filters Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-browse.html Retrieve browse results based on a filter name and value, with options for pagination and additional filters. Use this to display products matching specific criteria. ```javascript constructorio.browse.getBrowseResults('group_id', 't-shirts', { resultsPerPage: 40, filters: { size: 'medium' }, filterMatchTypes: { size: 'all' } }); ``` -------------------------------- ### ConstructorIO Client Instantiation Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/constructorio.js.html Instantiate the Constructor.io client with various configuration options. This includes essential parameters like apiKey and optional settings for service URLs, user segments, test cells, client ID, session ID, user ID, fetch implementation, tracking delays, and network parameters. ```javascript /** * @param {object} parameters - Parameters for client instantiation * @param {string} parameters.apiKey - Constructor.io API key * @param {string} [parameters.serviceUrl='https://ac.cnstrc.com'] - API URL endpoint * @param {string} [parameters.quizzesServiceUrl='https://quizzes.cnstrc.com'] - Quizzes API URL endpoint * @param {string} [parameters.agentServiceUrl='https://agent.cnstrc.com'] - AI Shopping Agent API URL endpoint * @param {string} [parameters.mediaServiceUrl='https://media-cnstrc.com'] - Media API URL endpoint * @param {string} [parameters.assistantServiceUrl='https://assistant.cnstrc.com'] - AI Shopping Assistant API URL endpoint @deprecated This parameter is deprecated and will be removed in a future version. Use parameters.agentServiceUrl instead. * @param {array} [parameters.segments] - User segments * @param {object} [parameters.testCells] - User test cells * @param {string} [parameters.clientId] - Client ID, defaults to value supplied by 'constructorio-id' module * @param {number} [parameters.sessionId] - Session ID, defaults to value supplied by 'constructorio-id' module * @param {string} [parameters.userId] - User ID * @param {function} [parameters.fetch] - If supplied, will be utilized for requests rather than default Fetch API * @param {number} [parameters.trackingSendDelay=250] - Amount of time to wait before sending tracking events (in ms) * @param {boolean} [parameters.sendReferrerWithTrackingEvents=true] - Indicates if the referrer is sent with tracking events * @param {boolean} [parameters.sendTrackingEvents=false] - Indicates if tracking events should be dispatched * @param {object} [parameters.idOptions] - Options object to be supplied to 'constructorio-id' module * @param {object} [parameters.eventDispatcher] - Options related to 'EventDispatcher' class * @param {boolean} [parameters.eventDispatcher.enabled=true] - Determine if events should be dispatched * @param {boolean} [parameters.eventDispatcher.waitForBeacon=true] - Wait for beacon before dispatching events * @param {object} [parameters.networkParameters] - Parameters relevant to network requests * @param {number} [parameters.networkParameters.timeout] - Request timeout (in milliseconds) - may be overridden within individual method calls * @param {string} [parameters.humanityCheckLocation='session'] - Storage location for the humanity check flag ('session' for sessionStorage, 'local' for localStorage) * @property {object} search - Interface to {@link module:search} * @property {object} browse - Interface to {@link module:browse} * @property {object} autocomplete - Interface to {@link module:autocomplete} * @property {object} recommendations - Interface to {@link module:recommendations} * @property {object} tracker - Interface to {@link module:tracker} * @property {object} quizzes - Interface to {@link module:quizzes} * @property {object} agent - Interface to {@link module:agent} * @property {object} assistant - Interface to {@link module:assistant} @deprecated This property is deprecated and will be removed in a future version. Use the agent property instead. * @returns {class} */ constructor(options = {}) { const { apiKey, version: versionFromOptions, serviceUrl, quizzesServiceUrl, agentServiceUrl, assistantServiceUrl, mediaServiceUrl, segments, testCells, clientId, sessionId, userId, fetch: fetchFromOptions, ``` -------------------------------- ### Get Browse Facets Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-browse.html Retrieve browse facets for refining search results. Use this to get available facets and their values for a given query. ```javascript constructorio.browse.getBrowseFacets({ page: 1, resultsPerPage: 10, }); ``` -------------------------------- ### Instantiate Constructor.io Client Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/README.md Create an instance of the Constructor.io client by providing your API key. This client is intended for browser environments. ```javascript const ConstructorioClient = require('@constructor-io/constructorio-client-javascript'); const constructorio = new ConstructorioClient({ apiKey: 'YOUR API KEY', }); ``` -------------------------------- ### Development and npm Commands Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/README.md Common npm commands for development, including preparing the environment, linting, testing, generating coverage reports, and building documentation. Note that lifecycle scripts are ignored by default for safety; run `npm run prepare` once to enable the pre-push lint hook. ```bash npm run prepare # one-time after cloning: install husky git hooks (pre-push lint) npm run lint # run lint on source code and tests npm run test # run tests npm run coverage # run tests and serves coverage reports from localhost:8081 npm run docs # output documentation to `./docs` directory ``` -------------------------------- ### Recommendations Class Constructor Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_recommendations.js.html Initializes the Recommendations module. It accepts an options object which may include an event dispatcher for handling events. ```javascript class Recommendations { constructor(options) { this.options = options || {}; this.eventDispatcher = new EventDispatcher(options.eventDispatcher); } /** * Get recommendations for supplied pod identifier * * @function getRecommendations * @description Retrieve recommendation results from Constructor.io API * @param {string} podId - Pod identifier * @param {object} [parameters] - Additional parameters to refine results * @param {string|array} [parameters.itemIds] - Item ID(s) to retrieve recommendations for (strategy specific). * Required for variationId * @param {string} [parameters.variationId] - Variation ID to retrieve recommendations for (strategy specific) * @param {number} [parameters.numResults] - The number of results to return * @param {string} [parameters.section] - The section to return results from * @param {string} [parameters.term] - The term to use to refine results (strategy specific) * @param {object} [parameters.filters] - Key / value mapping of filters used to refine results * @param {object} [parameters.variationsMap] - The variations map object to aggregate variations. Please refer to https://docs.constructor.com/reference/shared-variations-mapping for details * @param {object} [parameters.preFilterExpression] - Faceting expression to scope search results. Please refer to https://docs.constructor.com/reference/configuration-collections ``` -------------------------------- ### Get Browse Groups Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-browse.html Retrieve browse groups from the API. This is useful for navigating hierarchical data or collections. ```javascript constructorio.browse.getBrowseGroups({ filters: { group_id: 'drill_collection' }, fmtOptions: { groups_max_depth: 2 } }); ``` -------------------------------- ### ConstructorIO Constructor Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/ConstructorIO.html Instantiates the Constructor.IO client with various configuration options. ```APIDOC ## new ConstructorIO(parameters) ### Description Instantiates the Constructor.IO client. ### Parameters #### Parameters - **parameters** (object) - Parameters for client instantiation - **apiKey** (string) - Constructor.io API key - **serviceUrl** (string) - Optional - API URL endpoint. Defaults to 'https://ac.cnstrc.com' - **quizzesServiceUrl** (string) - Optional - Quizzes API URL endpoint. Defaults to 'https://quizzes.cnstrc.com' - **agentServiceUrl** (string) - Optional - AI Shopping Agent API URL endpoint. Defaults to 'https://agent.cnstrc.com' - **mediaServiceUrl** (string) - Optional - Media API URL endpoint. Defaults to 'https://media-cnstrc.com' - **assistantServiceUrl** (string) - Optional - AI Shopping Assistant API URL endpoint. Deprecated, use parameters.agentServiceUrl instead. Defaults to 'https://assistant.cnstrc.com' - **segments** (array) - Optional - User segments - **testCells** (object) - Optional - User test cells - **clientId** (string) - Optional - Client ID, defaults to value supplied by 'constructorio-id' module - **sessionId** (number) - Optional - Session ID, defaults to value supplied by 'constructorio-id' module - **userId** (string) - Optional - User ID - **fetch** (function) - Optional - If supplied, will be utilized for requests rather than default Fetch API - **trackingSendDelay** (number) - Optional - Amount of time to wait before sending tracking events (in ms). Defaults to 250 - **sendReferrerWithTrackingEvents** (boolean) - Optional - Indicates if the referrer is sent with tracking events. Defaults to true - **sendTrackingEvents** (boolean) - Optional - Indicates if tracking events should be dispatched. Defaults to false - **idOptions** (object) - Optional - Options object to be supplied to 'constructorio-id' module - **eventDispatcher** (object) - Optional - Options related to 'EventDispatcher' class - **enabled** (boolean) - Optional - Determine if events should be dispatched. Defaults to true - **waitForBeacon** (boolean) - Optional - Wait for beacon before dispatching events. Defaults to true - **networkParameters** (object) - Optional - Parameters relevant to network requests - **timeout** (number) - Optional - Request timeout (in milliseconds) - may be overridden within individual method calls - **humanityCheckLocation** (string) - Optional - Storage location for the humanity check flag ('session' for sessionStorage, 'local' for localStorage). Defaults to 'session' ### Returns - **class** - The instantiated Constructor.IO client class. ``` -------------------------------- ### NPM Development Commands Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/index.html Common npm commands for linting, testing, generating coverage reports, and building documentation for the client library. ```bash npm run lint # run lint on source code and tests ``` ```bash npm run test # run tests ``` ```bash npm run coverage # run tests and serves coverage reports from localhost:8081 ``` ```bash npm run docs # output documentation to `./docs` directory ``` -------------------------------- ### getQuizResults Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-quizzes.html Retrieve quiz recommendation and filter expression from the Constructor.io API. This method is used to get the final results of a quiz. ```APIDOC ## getQuizResults(quizId, parameters, networkParametersopt) ### Description Retrieve quiz recommendation and filter expression from Constructor.io API. ### Method Not specified (assumed to be a client-side SDK method) ### Parameters #### Path Parameters - **quizId** (string) - Required - The identifier of the quiz #### Query Parameters - **parameters** (string) - Additional parameters to refine result set ### Request Example ```javascript constructorio.quizzes.getQuizResults('quizId', { answers: [[1,2],[1]], section: '123', quizVersionId: '123', quizSessionId: '234' }); ``` ### Response #### Success Response (200) Type: Promise ``` -------------------------------- ### Initialize Constructor.io Client Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/constructorio.js.html Initializes the Constructor.io client with essential parameters like API key, service URLs, and user identification. It handles session and client ID generation based on the environment (DOM or DOM-less). ```javascript class ConstructorIO { constructor(options = {}) { const { apiKey, version: versionFromOptions, serviceUrl, quizzesServiceUrl, agentServiceUrl, assistantServiceUrl, mediaServiceUrl, sessionId, clientId, userId, segments, testCells, fetch: fetchFromOptions, trackingSendDelay, sendReferrerWithTrackingEvents, sendTrackingEvents, eventDispatcher, beaconMode, networkParameters, humanityCheckLocation, } = options; if (!apiKey || typeof apiKey !== 'string') { throw new Error('API key is a required parameter of type string'); } let session_id; let client_id; const versionFromGlobal = typeof global !== 'undefined' && global.CLIENT_VERSION; // Initialize ID session if DOM context is available if (helpers.canUseDOM()) { ({ session_id, client_id } = new ConstructorioID(idOptions || {})); } else { // Validate session ID is provided if (!sessionId || typeof sessionId !== 'number') { throw new Error('sessionId is a required user parameter of type number'); } // Validate client ID is provided if (!clientId || typeof clientId !== 'string') { throw new Error('clientId is a required user parameter of type string'); } } const normalizedServiceUrl = serviceUrl && serviceUrl.replace(///$/, ''); this.options = { apiKey, version: versionFromOptions || versionFromGlobal || computePackageVersion(), serviceUrl: helpers.addHTTPSToString(normalizedServiceUrl) || 'https://ac.cnstrc.com', quizzesServiceUrl: (quizzesServiceUrl && quizzesServiceUrl.replace(///$/, '')) || 'https://quizzes.cnstrc.com', agentServiceUrl: (agentServiceUrl && agentServiceUrl.replace(///$/, '')) || 'https://agent.cnstrc.com', assistantServiceUrl: (assistantServiceUrl && assistantServiceUrl.replace(///$/, '')) || 'https://assistant.cnstrc.com', mediaServiceUrl: (mediaServiceUrl && mediaServiceUrl.replace(///$/, '')) || 'https://media-cnstrc.com', sessionId: sessionId || session_id, clientId: clientId || client_id, userId, segments, testCells: helpers.toValidTestCells(testCells), fetch: fetchFromOptions || fetch, trackingSendDelay, sendTrackingEvents, sendReferrerWithTrackingEvents, eventDispatcher, beaconMode: (beaconMode === false) ? false : true, // Defaults to 'true', networkParameters: networkParameters || {}, humanityCheckLocation: humanityCheckLocation || 'session', }; // Expose global modules this.search = new Search(this.options); this.browse = new Browse(this.options); this.autocomplete = new Autocomplete(this.options); this.recommendations = new Recommendations(this.options); this.tracker = new Tracker(this.options); this.quizzes = new Quizzes(this.options); this.agent = new Agent(this.options); this.assistant = new Assistant(this.options); // Dispatch initialization event new EventDispatcher(options.eventDispatcher).queue('instantiated', this.options); } ``` -------------------------------- ### Get Voice Search Results Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-search.html Retrieve voice search results from the Constructor.io API. This method is designed for natural language queries. ```javascript constructorio.search.getVoiceSearchResults('show me lipstick'); ``` -------------------------------- ### Importing Constructor.io Modules Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/constructorio.js.html Import various modules and utilities from the Constructor.io client library. This includes core functionalities like search, browse, autocomplete, recommendations, tracker, quizzes, agent, and assistant, as well as utility functions for event dispatching and helpers. ```javascript const Search = require('./modules/search'); const Browse = require('./modules/browse'); const Autocomplete = require('./modules/autocomplete'); const Recommendations = require('./modules/recommendations'); const Tracker = require('./modules/tracker'); const EventDispatcher = require('./utils/event-dispatcher'); const helpers = require('./utils/helpers'); const { default: packageVersion } = require('./version'); const Quizzes = require('./modules/quizzes'); const Agent = require('./modules/agent'); const Assistant = require('./modules/assistant'); ``` -------------------------------- ### Recommendations.getRecommendations Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_recommendations.js.html Retrieves recommendation results from the Constructor.io API for a specified pod. This method allows for detailed refinement of recommendations through various parameters. ```APIDOC ## getRecommendations ### Description Retrieve recommendation results from Constructor.io API for a supplied pod identifier. This method allows for detailed refinement of recommendations through various parameters. ### Method `POST` (Implicitly, as it constructs a URL for an API call) ### Endpoint `/recommendations/v1/pods/{podId}` ### Parameters #### Path Parameters - **podId** (string) - Required - The identifier for the recommendation pod. #### Query Parameters - **apiKey** (string) - Required - The API key for authentication. - **version** (string) - Required - The API version to use. - **c** (string) - Required - Alias for version. - **i** (string) - Required - Client ID. - **s** (string) - Required - Session ID. - **us** (array) - Optional - User segments. - **ui** (string) - Optional - User ID. - **num_results** (number) - Optional - The number of results to return. - **item_id** (string|array) - Optional - Item ID(s) to retrieve recommendations for. Required for `variationId`. - **variation_id** (string) - Optional - Variation ID to retrieve recommendations for. Requires `itemIds`. - **section** (string) - Optional - The section to return results from. - **term** (string) - Optional - The term to use to refine results. - **filters** (object) - Optional - Key/value mapping of filters used to refine results. - **fmt_options** (object) - Optional - Formatting options for the response. - **fmt_options.hidden_fields** (array) - Optional - Fields to hide in the response. - **variations_map** (object) - Optional - The variations map object to aggregate variations. - **pre_filter_expression** (object) - Optional - Faceting expression to scope search results. ### Request Example ```json { "apiKey": "YOUR_API_KEY", "version": "v2", "serviceUrl": "https://ac.cnstr.io", "sessionId": "YOUR_SESSION_ID", "userId": "YOUR_USER_ID", "clientId": "YOUR_CLIENT_ID", "segments": ["segment1", "segment2"], "podId": "your-pod-id", "parameters": { "numResults": 10, "itemIds": "item123", "variationId": "variationXYZ", "section": "products", "term": "shoes", "filters": { "color": "red" }, "variationsMap": { "attribute": "color" }, "preFilterExpression": { "or": [ { "and": [ { "field": "price", "operator": ">", "value": 10 } ] } ] } } } ``` ### Response #### Success Response (200) - **results** (array) - The list of recommendation results. - **pod** (object) - Information about the recommendation pod. - **total_num_results** (number) - The total number of results available. - **search_details** (object) - Details about the search performed. #### Response Example ```json { "results": [ { "item_id": "item123", "title": "Example Item", "image_url": "http://example.com/image.jpg", "is_tracked": true } ], "pod": { "id": "your-pod-id" }, "total_num_results": 50, "search_details": { "request_id": "abc123xyz789" } } ``` ``` -------------------------------- ### getRecommendations Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-recommendations.html Retrieve recommendation results from Constructor.io API. This method allows for flexible refinement of recommendations using various parameters. ```APIDOC ## getRecommendations(podId, parametersopt, networkParametersopt) ### Description Retrieve recommendation results from Constructor.io API. ### Method (Implicitly a method call within the SDK, not an HTTP method) ### Endpoint (Not applicable, SDK method) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ##### Parameters: - **podId** (string) - Required - Pod identifier - **parameters** (object) - Optional - Additional parameters to refine results - **itemIds** (string | array) - Optional - Item ID(s) to retrieve recommendations for (strategy specific). Required for variationId - **variationId** (string) - Optional - Variation ID to retrieve recommendations for (strategy specific) - **numResults** (number) - Optional - The number of results to return - **section** (string) - Optional - The section to return results from - **term** (string) - Optional - The term to use to refine results (strategy specific) - **filters** (object) - Optional - Key / value mapping of filters used to refine results - **variationsMap** (object) - Optional - The variations map object to aggregate variations. Please refer to https://docs.constructor.com/reference/shared-variations-mapping for details - **preFilterExpression** (object) - Optional - Faceting expression to scope search results. Please refer to https://docs.constructor.com/reference/configuration-collections - **fmtOptions** (object) - Optional - An object containing options to format different aspects of the response. Please refer to https://docs.constructor.com/reference/v1-recommendations-get-pod-results for details - **hiddenFields** (Array.) - Optional - Hidden metadata fields to return - **networkParameters** (object) - Optional - Parameters relevant to the network request - **timeout** (number) - Optional - Request timeout (in milliseconds) ### Request Example ```javascript constructorio.recommendations.getRecommendations('t-shirt-best-sellers', { numResults: 5, filters: { size: 'medium' }, }); ``` ### Response #### Success Response (200) (Type: Promise) #### Response Example (Not provided in source) ``` -------------------------------- ### Get Next Quiz Question Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_quizzes.js.html Retrieves the next question for a given quiz. It handles network timeouts and ensures the response data is in the expected format. ```javascript constructorio.quizzes.getQuizNextQuestion('quizId', { answers: [[1,2],[1]], section: '123', quizVersionId: '123', quizSessionId: '1234', }); ``` -------------------------------- ### getQuizAllQuestions Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-quizzes.html Retrieve all questions for a particular quiz from the Constructor.io API. This method is useful for fetching the entire set of questions for a quiz at once. ```APIDOC ## getQuizAllQuestions(quizId, parameters, networkParametersopt) ### Description Retrieve all questions for a particular quiz from Constructor.io API. ### Method Not specified (assumed to be a client-side SDK method) ### Parameters #### Path Parameters - **quizId** (string) - Required - The identifier of the quiz #### Query Parameters - **parameters** (object) - Optional - Additional parameters - **section** (string) - Optional - Product catalog section - **quizVersionId** (string) - Optional - Version identifier for the quiz. - **quizSessionId** (string) - Optional - Session identifier for the quiz. - **networkParameters** (object) - Optional - Parameters relevant to the network request - **timeout** (number) - Optional - Request timeout (in milliseconds) ### Request Example ```javascript constructorio.quizzes.getQuizAllQuestions('quizId', { quizVersionId: '123' }); ``` ### Response #### Success Response (200) Type: Promise ``` -------------------------------- ### Get Browse Results with Filters (JavaScript) Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_browse.js.html Retrieves browse results from the API using specified filters. Ensure the `createBrowseUrlFromFilter` function is available and correctly configured. ```javascript requestUrl = createBrowseUrlFromFilter(filterName, filterValue, parameters, this.options); } return fetch(requestUrl, { signal }) .then(helpers.convertResponseToJson) .then((json) => { if (json.response && json.response.results) { if (json.result_id) { // Append `result_id` to each result item json.response.results.forEach((result) => { // eslint-disable-next-line no-param-reassign result.result_id = json.result_id; }); } this.eventDispatcher.queue('browse.getBrowseResults.completed', json); return json; } throw new Error('getBrowseResults response data is malformed'); }); ``` -------------------------------- ### Get Search Results Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_search.js.html Retrieves search results for a given query with optional parameters for filtering, sorting, and formatting. Handles network timeouts and response processing. ```javascript constructorio.search.getSearchResults('t-shirt', { resultsPerPage: 40, filters: { size: 'medium' }, filterMatchTypes: { size: 'all' } }); ``` ```javascript getSearchResults(query, parameters, networkParameters = {}) { let requestUrl; const { fetch } = this.options; let signal; if (typeof AbortController === 'function') { const controller = new AbortController(); signal = controller && controller.signal; // Handle network timeout if specified helpers.applyNetworkTimeout(this.options, networkParameters, controller); } try { requestUrl = createSearchUrl(query, parameters, this.options); } catch (e) { return Promise.reject(e); } return fetch(requestUrl, { signal }) .then(helpers.convertResponseToJson) .then((json) => { // Search results if (json.response && json.response.results) { if (json.result_id) { // Append `result_id` to each result item json.response.results.forEach((result) => { // eslint-disable-next-line no-param-reassign result.result_id = json.result_id; }); } this.eventDispatcher.queue('search.getSearchResults.completed', json); return json; } // Redirect rules if (json.response && json.response.redirect) { this.eventDispatcher.queue('search.getSearchResults.completed', json); return json; } throw new Error('getSearchResults response data is malformed'); }); } ``` -------------------------------- ### Expose Constructor.io Client Globally Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/constructorio.js.html Exposes the Constructor.io client class to the global `window` object if the DOM is available. This allows for easier access and integration in browser environments. ```javascript // Expose on window object if available if (helpers.canUseDOM()) { window.ConstructorioClient = ConstructorIO; } ``` -------------------------------- ### Get Browse Facet Options Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-browse.html Retrieve facet options for a given facet name. This method is useful for understanding the available filter values for a specific facet. ```javascript constructorio.browse.getBrowseFacetOptions('price', { }); ``` -------------------------------- ### setClientOptions(options) Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/ConstructorIO.html Updates the client's configuration options after instantiation. ```APIDOC ## setClientOptions(options) ### Description Sets the client options. ### Parameters #### Parameters - **options** (object) - Client options to update - **apiKey** (string) - Optional - Constructor.io API key - **segments** (array) - Optional - User segments - **testCells** (object) - Optional - User test cells - **sessionId** (number) - Optional - Session ID - Will only be set in DOM-less environments - **userId** (string) - Optional - User ID - **sendTrackingEvents** (boolean) - Optional - Indicates if tracking events should be dispatched ``` -------------------------------- ### Update Constructor.io Client Options Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/constructorio.js.html Allows updating specific client options after initialization. This method is useful for dynamically changing parameters like API key, segments, or tracking event behavior. ```javascript /** * Sets the client options * * @param {object} options - Client options to update * @param {string} [options.apiKey] - Constructor.io API key * @param {array} [options.segments] - User segments * @param {object} [options.testCells] - User test cells * @param {number} [options.sessionId] - Session ID - Will only be set in DOM-less environments * @param {string} [options.userId] - User ID * @param {boolean} [options.sendTrackingEvents] - Indicates if tracking events should be dispatched */ setClientOptions(options) { if (Object.keys(options).length) { const { apiKey, segments, testCells, sessionId, userId, sendTrackingEvents } = options; if (apiKey) { this.options.apiKey = apiKey; } if (segments) { this.options.segments = segments; } if (testCells) { this.options.testCells = helpers.toValidTestCells(testCells); } if (typeof sendTrackingEvents === 'boolean') { this.options.sendTrackingEvents = sendTrackingEvents; this.tracker.requests.sendTrackingEvents = sendTrackingEvents; } // Set Session ID in dom-less environments only if (sessionId && !helpers.canUseDOM()) { this.options.sessionId = sessionId; } // If User ID is passed if ('userId' in options) { this.options.userId = userId; } } } ``` -------------------------------- ### Get Item with Overflow Fallback Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/utils_store.overflow.js.html Retrieves a value for a given key from the specified storage area. If an overflow area exists, it attempts to retrieve the value from there first. ```javascript _.get = function (area, key) { var overflow = _.overflow(area); return (overflow && _get.call(this, overflow, key)) || _get.apply(this, arguments); }; ``` -------------------------------- ### getBrowseFacets Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-browse.html Retrieve browse facets from the API. This method is used to get the available facets for a given browse query, which can include information like price ranges, sizes, or brands. ```APIDOC ## getBrowseFacets(parametersopt, networkParametersopt) ### Description Retrieve browse facets from API. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters (Method Arguments) - **parameters** (object) - Optional - Additional parameters to refine result set - **page** (number) - Optional - The page number of the results (Can't be used together with offset) - **offset** (number) - Optional - The number of results to skip from the beginning (Can't be used together with page) - **section** (string) - Optional - The section name for results. Defaults to 'Products'. - **fmtOptions** (object) - Optional - The format options used to refine result groups. Please refer to https://docs.constructor.com/reference/browse-browse-facets/ for details - **resultsPerPage** (number) - Optional - The number of results per page to return - **networkParameters** (object) - Optional - Parameters relevant to the network request - **timeout** (number) - Optional - Request timeout (in milliseconds) ### Request Example ```javascript constructorio.browse.getBrowseFacets({ page: 1, resultsPerPage: 10, }); ``` ### Response #### Success Response Type: Promise #### Response Example (Promise resolves with API response) ``` -------------------------------- ### trackAssistantResultLoadStarted Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-tracker.html Logs that the Assistant results page load has begun. This method is deprecated and will be removed in a future version; use trackAgentResultLoadStarted instead. ```APIDOC ## trackAssistantResultLoadStarted ### Description Logs that the Assistant results page load has begun (but has not necessarily loaded completely). ### Method (inner) ### Parameters #### Parameters - **parameters** (object) - Additional parameters to be sent with request - **intent** (string) - Intent of user request - **section** (string) - Optional. The section name for the item Ex. "Products" - **intentResultId** (string) - Optional. The intent result id from the ASA response - **networkParameters** (object) - Optional. Parameters relevant to the network request - **timeout** (number) - Optional. Request timeout (in milliseconds) ### Request Example ```javascript constructorio.tracker.trackAssistantResultLoadStarted({ intent: 'show me a recipe for a cookie', intentResultId: 'Zde93fd-f955-4020-8b8d-6b21b93cb5a2', }); ``` ### Returns Type: true | Error ``` -------------------------------- ### Get Browse Results for Item IDs Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-browse.html Retrieve browse results from the API using a list of item IDs. This snippet demonstrates how to apply filters and specify filter match types. ```javascript constructorio.browse.getBrowseResultsForItemIds(['shirt-123', 'shirt-456', 'shirt-789'], { filters: { size: 'medium' }, filterMatchTypes: { size: 'all' } }); ``` -------------------------------- ### Create Recommendations URL Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_recommendations.js.html Constructs the URL for the recommendations API endpoint. It takes a pod ID and various parameters to refine the recommendation query, including user segments, item IDs, and filtering options. Ensure all required parameters are provided to avoid errors. ```javascript function createRecommendationsUrl(podId, parameters, options) { const { apiKey, version, serviceUrl, sessionId, userId, clientId, segments } = options; let queryParams = { c: version }; queryParams.key = apiKey; queryParams.i = clientId; queryParams.s = sessionId; // Validate pod identifier is provided if (!podId || typeof podId !== 'string') { throw new Error('podId is a required parameter of type string'); } // Pull user segments from options if (segments && segments.length) { queryParams.us = segments; } // Pull user id from options and ensure string if (userId) { queryParams.ui = String(userId); } if (parameters) { const { numResults, itemIds, variationId, section, term, filters, variationsMap, hiddenFields, preFilterExpression, fmtOptions, } = parameters; // Pull num results number from parameters if (!helpers.isNil(numResults)) { queryParams.num_results = numResults; } // Pull item ids from parameters if (itemIds) { queryParams.item_id = itemIds; } if (variationId) { if (!itemIds || (typeof itemIds === 'string' && !itemIds.trim())) { throw new Error('itemIds is a required parameter for variationId'); } if (Array.isArray(itemIds) && !itemIds.length) { throw new Error('At least one itemId is a required parameter for variationId'); } queryParams.variation_id = variationId; } // Pull section from parameters if (section) { queryParams.section = section; } // Pull term from parameters if (term) { queryParams.term = term; } // Pull filters from parameters if (filters) { queryParams.filters = filters; } // Pull format options from parameters if (fmtOptions) { queryParams.fmt_options = fmtOptions; } // Pull hidden fields from parameters if (hiddenFields) { if (queryParams.fmt_options) { queryParams.fmt_options.hidden_fields = hiddenFields; } else { queryParams.fmt_options = { hidden_fields: hiddenFields }; } } // Pull variations map from parameters if (variationsMap) { queryParams.variations_map = JSON.stringify(variationsMap); } // Pull pre_filter_expression from parameters if (preFilterExpression) { queryParams.pre_filter_expression = JSON.stringify(preFilterExpression); } } queryParams = helpers.cleanParams(queryParams); const queryString = helpers.stringify(queryParams); return `${serviceUrl}/recommendations/v1/pods/${helpers.encodeURIComponentRFC3986(helpers.trimNonBreakingSpaces(podId))}?${queryString}`; } ``` -------------------------------- ### Retrieve Browse Results Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/modules_browse.js.html Retrieves browse results from the Constructor.io API. Supports various parameters for filtering, pagination, sorting, and formatting. Includes network request options like timeout and AbortController. ```javascript getBrowseResults(filterName, filterValue, parameters, networkParameters = {}) { let requestUrl; const { fetch } = this.options; let signal; if (typeof AbortController === 'function') { const controller = new AbortController(); signal = controller && controller.signal; // Handle network timeout if specified helpers.applyNetworkTimeout(this.options, networkParameters, controller); } try { ``` -------------------------------- ### getBrowseFacetOptions Source: https://github.com/constructor-io/constructorio-client-javascript/blob/master/docs/module-browse.html Retrieve facet options from the API for a given facet name. This method allows you to get specific options available for a particular facet, which can be useful for filtering or displaying facet choices to the user. ```APIDOC ## getBrowseFacetOptions(facetName, networkParametersopt, parametersopt) ### Description Retrieve facet options from API. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters (Method Arguments) - **facetName** (string) - Required - Name of the facet whose options to return - **networkParameters** (object) - Optional - Parameters relevant to the network request - **timeout** (number) - Optional - Request timeout (in milliseconds) - **parameters** (object) - Optional - Additional parameters to refine result set - **section** (string) - Optional - The section name for results. Defaults to 'Products'. - **fmtOptions** (object) - Optional - The format options used to refine result groups. Please refer to https://docs.constructor.com/reference/v1-browse-get-browse-facet-options for details ### Request Example ```javascript constructorio.browse.getBrowseFacetOptions('price', { }); ``` ### Response #### Success Response Type: Promise #### Response Example (Promise resolves with API response) ```