// Store API key; const CLIENT_API_KEY = 'a5cbba9ef8049f80e856'; // Allowed calls (e.g.: piacter('banner', ...) const supportedAPI = [ 'init', 'banner', 'ad-carousel', 'ad-self', 'profile' ]; const apiUrl = 'https://agrarpiacter.agroforum.hu/api/widget'; /** The main entry of the application */ function app(window) { // Default configurations let configurations = { }; let globalObject = window[window['AP-Widget']]; // Get the queued calls from the client let queue = globalObject.q; // Dispatch calls if (queue) { // API calls for (var i = 0; i < queue.length; i++) { apiHandler(queue[i][0], queue[i][1]); } } // Override temporary (until the app loaded) handler for widget's API calls globalObject = apiHandler; globalObject.configurations = configurations; } /** Method that handles all API calls */ function apiHandler(api, params) { // Validate API call if (!api) throw Error('API method required'); api = api.toLowerCase(); if (supportedAPI.indexOf(api) === -1) throw Error(`Method ${api} is not supported`); // Add key to params params.key = CLIENT_API_KEY; // Get response for the selected API from the server let url = apiUrl + '/' + api + '/' + new URLSearchParams(params).toString(); load(url, function(response) { // Dispatch job according to the selected API switch (api) { case 'banner': document.querySelector(params.container).insertAdjacentHTML('afterbegin', response); break; case 'ad-carousel': document.querySelector(params.container).insertAdjacentHTML('afterbegin', response); break; default: console.warn(`Api does not exist: ${api}`); } }) } /** * Add configuration passed in the init call */ function extendObject(a, b) { for (var key in b) if (b.hasOwnProperty(key)) a[key] = b[key]; return a; } /** * AJAX helper */ function load(url, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { callback(xhr.response); } }; xhr.open('GET', url, true); xhr.send(''); } /** * Run app */ app(window);