discord-client/webpack/lib/api-client.js

82 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-03-27 12:52:14 +00:00
import XHRClientDriver from './client/xhr.js'
export default class APIClient{
2018-03-21 17:44:27 +00:00
/* (1) Constructs an API client manager
*
*
* @return http_url<String> Built http_url
*
---------------------------------------------------------*/
2018-03-27 14:34:30 +00:00
constructor(_hostname){
2018-03-27 14:34:30 +00:00
this.xhr_driver = new XHRClientDriver(_hostname, true);
}
/* Server Transaction
*
* @param _path<String> target path (format "HTTP_METHOD uri/uri/uri")
2018-03-27 12:52:14 +00:00
* @param _form<Object> formdata object (as raw object)
* @param _callback<Function> Response callback
* @param _token<String> [OPT] http token
2018-03-21 17:44:27 +00:00
*
***************************************************************************************************
*
* @usecase
* 1. api.call(
* 2. 'PUT newspaper/article/4'
* 3. { content: "new content" },
* 4. (r) => alert(r.error),
* 5. 'sometoken'
2018-03-21 17:44:27 +00:00
* 6. );
*
*/
2018-03-27 14:34:30 +00:00
call(_path, _form, _callback, _token=null){
2018-03-21 17:44:27 +00:00
/* (1) Argument management
2018-03-21 17:44:27 +00:00
---------------------------------------------------------*/
/* (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); };
2018-03-21 17:44:27 +00:00
2018-03-27 14:34:30 +00:00
var persist = { received: false };
2018-03-27 12:52:14 +00:00
/* (2) Bind callbacks */
this.xhr_driver.onreceive = function(_response){
2018-03-21 17:44:27 +00:00
2018-03-27 14:34:30 +00:00
this.received = true;
2018-03-27 12:52:14 +00:00
/* 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;
}
2018-03-21 17:44:27 +00:00
2018-03-27 12:52:14 +00:00
/* Launch @_callback with response */
_callback(_response);
2018-03-21 17:44:27 +00:00
2018-03-27 14:34:30 +00:00
}.bind(persist);
2018-03-21 17:44:27 +00:00
this.xhr_driver.onclose = function(){ !this.received && _callback({ error: -3 }); }.bind(persist);
2018-03-21 17:44:27 +00:00
2018-03-27 12:52:14 +00:00
return this.xhr_driver.send({
path: _path,
form: _form,
http_token: _token
});
2018-03-21 17:44:27 +00:00
}
}