/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /** * Get the API endpoint URL for an action * @param {String} action * @return {String} */ function getActionUrl(action) { return SETTINGS["server"] + "/" + action; } /** * Call an API function on the server. * @param {string} action * @param {array} data key: value array of arguments for the server. * @param {function} success Called with the JSON response object. * @param {function} failure Called with an error message string. * @return {undefined} */ function callAPI(action, data, success, failure) { return $.ajax({ type: 'POST', dataType: 'json', url: getActionUrl(action), data: data, timeout: 5000, success: function (data, textStatus) { if (data.status === "OK") { success(data); return; } if (typeof failure != 'function') { return; } if (data.status === "ERROR") { failure(data.msg); } else { failure("The server sent an invalid response."); } }, error: function (xhr, textStatus, errorThrown) { if (typeof failure != 'function') { return; } switch (textStatus) { case "timeout": failure("Couldn't connect to the server (timeout)."); break; case "error": failure("Couldn't connect to the server (error)."); break; case "parseerror": failure("The server sent a malformed response."); break; default: failure("Couldn't connect to the server."); } } }); } /** * Call an API function on the server. Makes fewer assumptions about what * constitutes a success response. * @param {string} action * @param {array} data key: value array of arguments for the server. * @param {function} success Called with the JSON response object. * @param {function} failure Called with an error message string. * @return {undefined} */ function callAPIRawResponse(action, data, success, failure) { return $.ajax({ type: 'POST', url: getActionUrl(action), data: data, timeout: 5000, success: function (data, textStatus) { success(data); }, error: function (xhr, textStatus, errorThrown) { if (typeof failure != 'function') { return; } switch (textStatus) { case "timeout": failure("Couldn't connect to the server (timeout)."); break; case "error": failure("Couldn't connect to the server (error)."); break; case "parseerror": failure("The server sent a malformed response."); break; default: failure("Couldn't connect to the server."); } } }); }