/** * Handle server requests in the context of the application * @type {{}} */ mods.server = function($) { /** * Called when there is an error * @param res */ function handleError(res) { var code = res.status; switch (code) { case 401: // Authentication error - need login handleAuthenticationError(); break; case 403: // not authorized to perform operation handleForbidden(); break; default: // unhandled error handleUnexpectedError(); } } /** * Called when there is a 401 code return from the server */ function handleAuthenticationError() { // if there is an authentication error, go to the login page window.location.href = window.appconfig.context + '/login.seam'; } function handleForbidden() { mods.app.showMessage({ title: 'Acesso negado', message: 'You don\'t have permission for this.', type: 'OK' }); } function handleUnexpectedError() { mods.app.showMessage({ title: 'Erro inesperado', message: 'An unexpected error occurred. Try again in a few minutes.', type: 'OK' }); } function fetch(url, type, data, callback, callbackError) { $.ajax({ type: type, url: window.appconfig.context + '/resources/api' + url, dataType: 'json', data: JSON.stringify(data), cache: false, error: function(err) { var handled = callbackError && !!callbackError(err); if (!handled) { handleError(err); } }, contentType: 'application/json', success: callback }); } return { /** * Perform a POST to a server API expecting to send and receive a json data * @param url the API url, under the prefix /resources/api * @param data the data to be sent as json to the server * @param callback the function to be called when the request is completed */ post: function(url, data, callback, cberror) { fetch(url, 'POST', data, callback, cberror); }, /** * Perform a GET to the server expecting to receive a json data * @param url the API url, under the prefix /resources/api * @param callback the function to be called when the request is completed */ get: function(url, callback, cberror) { fetch(url, 'GET', null, callback, cberror); } }; }(jQuery);