Removed DEBUG

This commit is contained in:
xdrm-brackets 2018-03-27 14:52:14 +02:00
parent bd9f03235e
commit 5fcd1e363b
5 changed files with 31 additions and 192 deletions

View File

@ -1,79 +1,18 @@
/* classe API */
import XHRClientDriver from './client/xhr.js'
export default class APIClient{
/* (1) Constructs an API client manager
*
* @_hostname<String> Server hostname (without http, port number, etc)
* @_baseuri<String> Server base URI
* @_ssl<bool> [OPT] Whether SSL is activated (http vs https) (default: https)
* @_port<int> [OPT] optional HTTP port (default: none)
*
* @return http_url<String> Built http_url
*
---------------------------------------------------------*/
constructor(_hostname, _baseuri, _ssl=true, _port=null){
constructor(_hostname, _auth){
/* (1) Build URL parts */
this.http_parts = {
ssl: _ssl === true,
hostname: _hostname,
baseuri: this.fix_uri(_baseuri),
port: !isNaN(_port) ? _port: null
};
this.xhr_stack = []; // Ajax request stack
this.buffer = null; // Last request buffer
}
fix_uri(_uri){
if( typeof _uri !== 'string' )
return '';
return _uri.split('/').filter((r) => r.trim().length).join('/')
}
/* (2) HTTP url dynamic getter
*
* @_uri<String> [OPT] optional URI string
* @_token<String> [OPT] optional HTTP token
*
* @return http_url<String> Built http_url
*
---------------------------------------------------------*/
build_url(_uri, _token=null){
/* (1) Initialize URL buffer */
let bufurl = 'http';
/* (2) Manage @ssl */
this.http_parts.ssl && ( bufurl = bufurl.concat('s') );
bufurl = bufurl.concat('://');
/* (3) Manage token */
( typeof _token === 'string' ) && ( bufurl = bufurl.concat(`${_token}@`) );
/* (4) Manage hostname */
bufurl = bufurl.concat(this.http_parts.hostname);
/* (5) Manage port */
( this.http_parts.port !== null ) && ( bufurl = bufurl.concat(`:${this.http_parts.port}`) );
/* (6) Base uri */
bufurl = bufurl.concat(`/${this.http_parts.baseuri}/`);
/* (7) Manage URI */
bufurl = bufurl.concat( this.fix_uri(_uri) );
return bufurl;
this.xhr_driver = new XHRClientDriver(_hostname, _auth);
}
@ -82,7 +21,7 @@ export default class APIClient{
/* Server Transaction
*
* @param _path<String> target path (format "HTTP_METHOD uri/uri/uri")
* @param _args<Object> formdata object (as raw object)
* @param _form<Object> formdata object (as raw object)
* @param _callback<Function> Response callback
* @param _token<String> [OPT] http token
*
@ -97,7 +36,7 @@ export default class APIClient{
* 6. );
*
*/
call(_path, _args, _callback, _token=null){
call(_path, _form={}, _callback, _token=null){
/* (1) Argument management
@ -106,110 +45,25 @@ export default class APIClient{
if( !(_callback instanceof Function) )
_callback = function(r){ console.warn('The API callback function is missing, default callback set.', 'Response', r); };
/* (2) Check @path format */
if( !/^([A-Z]+) (.+)/i.test(_path) ){
_callback({ error: -1 });
return false;
}
/* (2) Bind callbacks */
this.xhr_driver.onreceive = function(_response){
var http_method = RegExp.$1;
var http_uri = RegExp.$2;
/* Try to parse JSON */
try{ _response = JSON.parse(_response); }catch(e){ _callback({error: -1}); }
/* (3) Default @_token */
if( typeof _token !== 'string' )
_token = null;
/* (3) Create form data
---------------------------------------------------------*/
/* (1) Create virtual form */
var form_data = new FormData();
/* (2) Add attributes */
for( var key in _args ){
// {2.1} If a file -> send as it //
if( _args[key] instanceof File )
form_data.append(key, _args[key]);
// {2.2} Else -> JSON stringify //
else
form_data.append(key, JSON.stringify(_args[key]));
/* Launch @_callback with response */
_callback(_response);
}
this.xhr_driver.onclose = function(){ _callback({ error: -2 }); }
/* (4) Create XHR request
---------------------------------------------------------*/
/* (1) Clean ended requests */
for( var i = this.xhr_stack.length-1 ; i >= 0 ; i-- ){
if( this.xhr_stack[i] != null )
break;
this.xhr_stack.pop();
}
/* (2) Push a new entry -> fetch its index */
i = this.xhr_stack.push(null) - 1;
/* (3) Create XHR object */
this.xhr_stack[i] = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttpRequest');
/* (5) Bind response event
---------------------------------------------------------*/
this.xhr_stack[i].onreadystatechange = function(i, parent){
/* (1) If request over */
if( this[i].readyState === 4 ){
/* (2) Update buffer (for debug) */
parent.buffer = this[i].responseText;
/* (3) If request success */
if( [0, 200].indexOf(this[i].status) > -1 ){
/* (3.1) Create default response (if JSON error) */
var response = { error: -2 };
/* (3.2) Try to parse JSON */
try{ response = JSON.parse(this[i].responseText); }catch(e){}
/* (3.3) Launch @_callback with response */
_callback(response);
/* (4) If request error */
}else
_callback({ error: -3 });
/* (5) Notify current xhr instance is done */
this[i] = null;
}
}.bind(this.xhr_stack, i, this);
/* (6) Finish & send request
---------------------------------------------------------*/
/* (1) Open the XHR */
console.log(http_method, this.build_url(http_uri, _token));
this.xhr_stack[i].open(http_method, this.build_url(http_uri, _token), true);
/* (2) Custom header to notify we're using Ajax */
this.xhr_stack[i].setRequestHeader('X-Requested-With', 'XMLHttpRequest');
/* (3) Make the call */
this.xhr_stack[i].send(form_data);
return true;
return this.xhr_driver.send({
path: _path,
form: _form,
http_token: _token
});
}

View File

@ -2,9 +2,6 @@ import ClientDriver from './client-driver.js'
export default class XHRClientDriver extends ClientDriver{
static get DEBUG(){ return true; }
/* (1) Creates a client driver
*
* @_resource<String> Target resource
@ -138,15 +135,16 @@ export default class XHRClientDriver extends ClientDriver{
let is_formdata = is_object && _request.form instanceof FormData;
/* (2) Create default value for _request.form */
let form_data = new FormData();
var form_data = new FormData();
/* (3) If already FormData object -> store as it is */
if( is_object && is_formdata )
form_data = _requset.form;
form_data = _request.form;
/* (4) If just a raw object -> convert to FormData */
if( is_object && !is_formdata )
Object.keys(_request.form).map( (k, v) => form_data.append(k, v) );
Object.keys(_request.form).map( (k) => form_data.append(k, _request.form[k]) );
/* (4) Open connection
@ -163,10 +161,6 @@ export default class XHRClientDriver extends ClientDriver{
/* (4) Send request */
this.xhr.send(form_data);
/* (5) DEBUG */
( XHRClientDriver.DEBUG ) && console.log(`XHRClientDriver.send(url '${protocol}${request_uri}', form '`, form_data, `'`);
return true;
}

View File

@ -110,6 +110,8 @@ gs.get.login.func.login = function(){
/* (3) API bindings */
api.onreceive = function(_response){
_response = JSON.parse(_response);
// manage error
if( _response.error !== 0 || _response.token == null )
return gs.get.router.push('register');

View File

@ -124,30 +124,18 @@ gs.get.register.func.register = function(){
return false;
/* (3) API bindings */
api.onreceive = function(_response){
_response = JSON.parse(_response);
api.call('POST /user', { username: username, password: password }, function(rs){
// manage error
if( _response.error !== 0 || _response.uid == null || _response.token == null )
if( rs.error !== 0 || rs.uid == null || rs.token == null )
return gs.get.router.push('register');
// manage login
gstore.set('uid', _response.uid);
auth.token = _response.token;
gstore.set('uid', rs.uid);
auth.token = rs.token;
document.location = '';
};
}, auth.toen);
api.onclose = function(){ return gs.get.router.push('register'); };
/* (4) API call */
api.send({
path: 'POST /user',
form: {
username: username,
password: password
}
});
}.bind(gs.get.register);

View File

@ -7,6 +7,7 @@ import routes from './routes'
import Authentication from './lib/authentication.js'
import XHRClientDriver from './lib/client/xhr.js'
import WebSocketClientDriver from './lib/client/ws.js'
import APIClient from './lib/api-client.js'
@ -23,7 +24,7 @@ window.xhrcd = XHRClientDriver;
window.wscd = WebSocketClientDriver;
/* (4) ClientDriver instances */
window.api = new XHRClientDriver('api.douscord.xdrm.io');
window.api = new APIClient('api.douscord.xdrm.io');
window.ws = new WebSocketClientDriver('ws.douscord.xdrm.io');