75 lines
1.7 KiB
JavaScript
75 lines
1.7 KiB
JavaScript
import XHRClientDriver from './client/xhr.js'
|
|
|
|
export default class APIClient{
|
|
|
|
|
|
|
|
/* (1) Constructs an API client manager
|
|
*
|
|
*
|
|
* @return http_url<String> Built http_url
|
|
*
|
|
---------------------------------------------------------*/
|
|
constructor(_hostname){
|
|
|
|
this.xhr_driver = new XHRClientDriver(_hostname, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Server Transaction
|
|
*
|
|
* @param _path<String> target path (format "HTTP_METHOD uri/uri/uri")
|
|
* @param _form<Object> formdata object (as raw object)
|
|
* @param _callback<Function> Response callback
|
|
* @param _token<String> [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: -1}); }
|
|
|
|
/* Launch @_callback with response */
|
|
_callback(_response);
|
|
|
|
}.bind(persist);
|
|
|
|
this.xhr_driver.onclose = function(){ !this.received && _callback({ error: -2 }); }.bind(persist);
|
|
|
|
|
|
return this.xhr_driver.send({
|
|
path: _path,
|
|
form: _form,
|
|
http_token: _token
|
|
});
|
|
|
|
}
|
|
|
|
|
|
} |