import XHRClientDriver from './client/xhr.js' export default class APIClient{ /* (1) Constructs an API client manager * * * @return http_url Built http_url * ---------------------------------------------------------*/ constructor(_hostname){ this.xhr_driver = new XHRClientDriver(_hostname, true); } /* Server Transaction * * @param _path target path (format "HTTP_METHOD uri/uri/uri") * @param _form formdata object (as raw object) * @param _callback Response callback * @param _token [OPT] http token * *************************************************************************************************** * * @usecase * 1. api.call( * 2. 'PUT newspaper/article/4' * 3. { content: "new content" }, * 4. (r) => alert(r.error), * 5. 'sometoken' * 6. ); * */ call(_path, _form, _callback, _token=null){ /* (1) Argument management ---------------------------------------------------------*/ /* (1) Set default callback if @callback not callable */ if( !(_callback instanceof Function) ) _callback = function(r){ console.warn('The API callback function is missing, default callback set.', 'Response', r); }; var persist = { received: false }; /* (2) Bind callbacks */ this.xhr_driver.onreceive = function(_response){ this.received = true; /* Try to parse JSON */ try{ _response = JSON.parse(_response); }catch(e){ _callback({error: -2}); } /* If authentication failed -> logout user*/ if( typeof _response.error === 'number' && _response.error === -1 ){ auth.token = null; document.location = ''; return; } /* Launch @_callback with response */ _callback(_response); }.bind(persist); this.xhr_driver.onclose = function(){ !this.received && _callback({ error: -3 }); }.bind(persist); return this.xhr_driver.send({ path: _path, form: _form, http_token: _token }); } }