Commit 7f84de14 authored by Thomas Lechauve's avatar Thomas Lechauve

Added a route system to vifib application

parent 3e8436aa
;(function($) { (function ($) {
"use strict";
var methods = { var methods = {
init: function( options ){ init: function (options) {
var settings = $.extend({ var settings = $.extend({
'host': '', 'host': '',
'access_token': '', 'access_token': '',
'clientID': '' 'clientID': ''
}, options); }, options);
return this.each(function(){ return this.each(function () {
methods['store'] = Modernizr.localstorage ? methods.lStore : methods.cStore; var setting;
for(var setting in settings){ methods.store = Modernizr.localstorage ? methods.lStore : methods.cStore;
$(this).slapos('store', setting, settings[setting]); for (setting in settings) {
if (settings.hasOwnProperty(setting)) {
$(this).slapos('store', setting, settings[setting]);
}
} }
}); });
}, },
/* Getters & Setters shortcuts */ /* Getters & Setters shortcuts */
access_token: function( value ){ access_token: function (value) {
return $(this).slapos('store', 'access_token', value); return $(this).slapos('store', 'access_token', value);
}, },
host: function( value ){ host: function (value) {
return $(this).slapos('store', 'host', value); return $(this).slapos('store', 'host', value);
}, },
clientID: function( value ){ clientID: function (value) {
return $(this).slapos('store', 'clientID', value); return $(this).slapos('store', 'clientID', value);
}, },
/* Local storage method */ /* Local storage method */
lStore: function( name, value ) { lStore: function (name, value) {
if(Modernizr.localstorage) if (Modernizr.localstorage) {
return value == undefined ? window.localStorage[name] : window.localStorage[name] = value; return value === undefined ? window.localStorage[name] : window.localStorage[name] = value;
}
return false; return false;
}, },
/* Cookie storage method */ /* Cookie storage method */
cStore: function(name, value){ cStore: function (name, value) {
if(value != undefined){ if (value !== undefined) {
document.cookie = name+"="+value+";domain="+window.location.hostname+";path="+window.location.pathname; document.cookie = name + "=" + value + ";domain=" + window.location.hostname + ";path=" + window.location.pathname;
}else{ } else {
var i,x,y, cookies = document.cookie.split(';'); var i, x, y, cookies = document.cookie.split(';');
for(i=0; i<cookies.length; i++){ for (i = 0; i < cookies.length; i += 1) {
x = cookies[i].substr(0, cookies[i].indexOf('=')); x = cookies[i].substr(0, cookies[i].indexOf('='));
y = cookies[i].substr(cookies[i].indexOf('=')+1); y = cookies[i].substr(cookies[i].indexOf('=') + 1);
x=x.replace(/^\s+|\s+$/g,""); x = x.replace(/^\s+|\s+$/g, "");
if(x == name) return unescape(y); if (x === name) {
return unescape(y);
}
} }
} }
}, },
statusDefault: function(){ statusDefault: function () {
return { return {
0: function(){ console.error("status error code: 0"); }, 0: function () { console.error("status error code: 0"); },
404: function(){ console.error("status error code: Not Found !"); } 404: function () { console.error("status error code: Not Found !"); }
} };
}, },
request: function( type, url, callback, statusEvent, data ) { request: function (type, url, callback, statusCode, data) {
data = data || ''; data = data || '';
statusEvent = statusEvent || this.statusDefault; statusCode = statusCode || this.statusDefault;
return this.each(function(){ return this.each(function () {
$.ajax({ $.ajax({
url: $(this).slapos('host')+url, url: $(this).slapos('host') + url,
type: type, type: type,
contentType: 'application/octet-stream', contentType: 'application/octet-stream',
data: JSON.stringify(data), data: JSON.stringify(data),
dataType: 'json', dataType: 'json',
context: $(this), context: $(this),
beforeSend: function(xhr){ beforeSend: function (xhr) {
if( $(this).slapos("access_token") ) { if ($(this).slapos("access_token")) {
xhr.setRequestHeader("Authorization", $(this).slapos("store","token_type") + " " + $(this).slapos("access_token")); xhr.setRequestHeader("Authorization", $(this).slapos("store", "token_type") + " " + $(this).slapos("access_token"));
xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Accept", "application/json");
} }
}, },
statusCode: statusEvent, statusCode: statusCode,
success: callback success: callback
}); });
}); });
}, },
newInstance: function(data, callback, statusEvent){ newInstance: function (data, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/instance', callback, statusEvent, data); return $(this).slapos('request', 'POST', '/instance', callback, statusEvent, data);
}, },
deleteInstance: function(id, callback, statusEvent){ deleteInstance: function (id, callback, statusEvent) {
return $(this).slapos('request', 'DELETE', '/instance/'+id, callback, statusEvent); return $(this).slapos('request', 'DELETE', '/instance/' + id, callback, statusEvent);
}, },
getInstance: function(id, callback, statusEvent){ getInstance: function (id, callback, statusEvent) {
return $(this).slapos('request', 'GET', '/instance/'+id, callback, statusEvent); return $(this).slapos('request', 'GET', '/instance/' + id, callback, statusEvent);
}, },
getInstanceCert: function(id, callback, statusEvent){ getInstanceCert: function (id, callback, statusEvent) {
return $(this).slapos('request', 'GET', '/instance/'+id+'/certificate', callback, statusEvent); return $(this).slapos('request', 'GET', '/instance/' + id + '/certificate', callback, statusEvent);
}, },
bangInstance: function(id, log, callback, statusEvent){ bangInstance: function (id, log, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/instance/'+id+'/bang', callback, statusEvent, log); return $(this).slapos('request', 'POST', '/instance/' + id + '/bang', callback, statusEvent, log);
}, },
editInstance: function(id, data, callback, statusEvent){ editInstance: function (id, data, callback, statusEvent) {
return $(this).slapos('request', 'PUT', '/instance/'+id, callback, statusEvent, data); return $(this).slapos('request', 'PUT', '/instance/' + id, callback, statusEvent, data);
}, },
newComputer: function(data, callback, statusEvent){ newComputer: function (data, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/computer', callback, statusEvent, data); return $(this).slapos('request', 'POST', '/computer', callback, statusEvent, data);
}, },
getComputer: function(id, callback, statusEvent){ getComputer: function (id, callback, statusEvent) {
return $(this).slapos('request', 'GET', '/computer/'+id, callback, statusEvent); return $(this).slapos('request', 'GET', '/computer/' + id, callback, statusEvent);
}, },
editComputer: function(id, data, callback, statusEvent){ editComputer: function (id, data, callback, statusEvent) {
return $(this).slapos('request', 'PUT', '/computer/'+id, callback, statusEvent, data); return $(this).slapos('request', 'PUT', '/computer/' + id, callback, statusEvent, data);
}, },
newSoftware: function(computerId, data, callback, statusEvent){ newSoftware: function (computerId, data, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/computer/'+computerId+'/supply', callback, statusEvent, data); return $(this).slapos('request', 'POST', '/computer/' + computerId + '/supply', callback, statusEvent, data);
}, },
bangComputer: function(id, log, callback, statusEvent){ bangComputer: function (id, log, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/computer/'+id+'/bang', callback, statusEvent, log); return $(this).slapos('request', 'POST', '/computer/' + id + '/bang', callback, statusEvent, log);
}, },
computerReport: function(id, data, callback, statusEvent){ computerReport: function (id, data, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/computer/'+id+'/report', callback, statusEvent, data); return $(this).slapos('request', 'POST', '/computer/' + id + '/report', callback, statusEvent, data);
} }
}; };
$.fn.slapos = function(method){ $.fn.slapos = function (method) {
if ( methods[method] ) { if (methods[method]) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if ( typeof method === 'object' || ! method ) { } else if (typeof method === 'object' || !method) {
return methods.init.apply( this, arguments ); return methods.init.apply(this, arguments);
} else { } else {
$.error( 'Method ' + method + ' does not exist on jQuery.slapos' ); $.error('Method ' + method + ' does not exist on jQuery.slapos');
} }
}; };
})(jQuery); })(jQuery);
...@@ -157,7 +157,7 @@ ...@@ -157,7 +157,7 @@
<li><a href="#"><i class="icon-star"></i>Favorites</a></li> <li><a href="#"><i class="icon-star"></i>Favorites</a></li>
<li class="nav-header">Services</li> <li class="nav-header">Services</li>
<li><a href="#"><i class="icon-list"></i>List all services</a></li> <li><a href="#"><i class="icon-list"></i>List all services</a></li>
<li><a href="#service"><i class="icon-plus-sign"></i>Add new service</a></li> <li><a href="#/service"><i class="icon-plus-sign"></i>Add new service</a></li>
<li><a href="#"><i class="icon-star"></i>Favorites</a></li> <li><a href="#"><i class="icon-star"></i>Favorites</a></li>
<ul style="list-style: none"> <ul style="list-style: none">
<li><a href="#service/200"><i class="icon-"></i>inst-0</a></li> <li><a href="#service/200"><i class="icon-"></i>inst-0</a></li>
......
...@@ -68,17 +68,17 @@ var inst1 = ...@@ -68,17 +68,17 @@ var inst1 =
tap_interface: "tap2"} tap_interface: "tap2"}
}; };
/*var fakeserver = sinon.fakeServer.create(); var fakeserver = sinon.fakeServer.create();
// Get instance // Get instance
fakeserver.respondWith("GET", "/instance/200",[200, {"Content-Type":"application/json; charset=utf-8"}, JSON.stringify(inst0)]); /*fakeserver.respondWith("GET", "/instance/200",[200, {"Content-Type":"application/json; charset=utf-8"}, JSON.stringify(inst0)]);
fakeserver.respondWith("GET", "/instance/201",[200, {"Content-Type":"application/json; charset=utf-8"}, JSON.stringify(inst1)]); fakeserver.respondWith("GET", "/instance/201",[200, {"Content-Type":"application/json; charset=utf-8"}, JSON.stringify(inst1)]);
// Get instance FAIL // Get instance FAIL
fakeserver.respondWith("GET", "/instance/408",[408, {"Content-Type":"application/json; charset=utf-8"}, "NOT FOUND"]); fakeserver.respondWith("GET", "/instance/408",[408, {"Content-Type":"application/json; charset=utf-8"}, "NOT FOUND"]);
fakeserver.respondWith("GET", "/instance/401",[401, {"Content-Type":"application/json; charset=utf-8"}, "NEED AUTH"]); fakeserver.respondWith("POST", "/instance",[401, {"Content-Type":"application/json; charset=utf-8"}, "NEED AUTH"]);
var tmp = $.ajax; var tmp = $.ajax;
/*$.ajax = function(url, options){ $.ajax = function(url, options){
var result = tmp(url, options); var result = tmp(url, options);
fakeserver.respond(); fakeserver.respond();
return result; return result;
......
...@@ -3,18 +3,34 @@ ...@@ -3,18 +3,34 @@
* Author: Thomas Lechauve * Author: Thomas Lechauve
* Date: 4/17/12 * Date: 4/17/12
*/ */
;(function($) { (function($) {
var routes = {
"/service" : "displayForm",
"/service/:id" : "displayData"
}
var router = function(e, d){
var $this = $(this);
$.each(routes, function(pattern, callback){
pattern = pattern.replace(/:\w+/g, '([^\/]+)');
var regex = new RegExp('^' + pattern + '$');
var result = regex.exec(d);
if (result) {
result.shift();
methods[callback].apply($this, result);
}
});
}
var methods = { var methods = {
init: function() { init: function() {
// Initialize slapos in this context // Initialize slapos in this context
$(this).slapos({host: '10.0.1.139:12002/erp5/portal_vifib_rest_api_v1'}); $(this).slapos({host: '10.0.1.139:12002/erp5/portal_vifib_rest_api_v1'});
var $this = $(this);
// Bind to urlChange event // Bind to urlChange event
return this.each(function(){ return this.each(function(){
var self = $(this);
$.subscribe("urlChange", function(e, d){ $.subscribe("urlChange", function(e, d){
if(d.route == "service" && d.id) { self.form('displayData', d.id); } router.call($this, e, d);
else if(d.route == "service") { self.form('displayForm'); }
}); });
$.subscribe("auth", function(e, d){ $.subscribe("auth", function(e, d){
$(this).form("authenticate", d); $(this).form("authenticate", d);
...@@ -22,23 +38,29 @@ ...@@ -22,23 +38,29 @@
}); });
}, },
authenticate: function(data){ authenticate: function(data) {
for(var d in data){ for (var d in data) {
$(this).slapos('store', d, data[d]); if (data.hasOwnProperty(d)) {
$(this).slapos('store', d, data[d]);
}
} }
}, },
displayData: function(id){ displayData: function(id){
var redirect = function(){
$(this).form('render', 'auth', {
'host':'t139:12002/erp5/web_site_module/hosting/request-access-token',
'client_id': 'client',
'redirect':escape(window.location.href)
})
};
var statusCode = {
401: redirect
};
$(this).html("<p>Ajax loading...</p>") $(this).html("<p>Ajax loading...</p>")
.slapos('getInstance', id, function(data){ .slapos('getInstance', id, function(data){
$(this).form('render', 'service', data); $(this).form('render', 'service', data);
}, {401: function(){ }, statusCode);
$(this).form('render', 'auth', {
'host':'t139:12002/erp5/web_site_module/hosting/request-access-token',
'client_id': 'client',
'redirect':escape(window.location.href)
})
}});
}, },
displayForm: function() { displayForm: function() {
...@@ -67,17 +89,22 @@ ...@@ -67,17 +89,22 @@
computer_id: "COMP-0", computer_id: "COMP-0",
} }
}; };
var redirect = function(){
$(this).form('render', 'auth', {
'host':'t139:12002/erp5/web_site_module/hosting/request-access-token',
'client_id': 'client',
'redirect':escape(window.location.href)
})
};
var statusCode = {
401: redirect
};
$.extend(request, data); $.extend(request, data);
$(this).html("<p>Requesting a new instance "+request["title"]+" ...</p>") $(this).html("<p>Requesting a new instance "+request["title"]+" ...</p>")
.slapos('newInstance', request, function(data){ .slapos('newInstance', request, function(data){
$(this).html(data);}, {401: function(){ $(this).html(data);},
$(this).form('render', 'auth', { statusCode
'host':'t139:12002/erp5/web_site_module/hosting/request-access-token', );
'client_id': 'client',
'redirect':escape(window.location.href)
})
}
});
}, },
render: function(template, data){ render: function(template, data){
......
...@@ -4,30 +4,28 @@ ...@@ -4,30 +4,28 @@
* Date: 4/18/12 * Date: 4/18/12
*/ */
;
// Hash parser utility // Hash parser utility
$.parseHash = function(hashTag){ $.parseHash = function(hashTag) {
var tokenized = $.extractAuth(hashTag); var tokenized = $.extractAuth(hashTag);
if( tokenized ){ if (tokenized) {
console.log(tokenized);
$.publish('auth', tokenized); $.publish('auth', tokenized);
} }
var splitted = hashTag.substr(1).split('/'); var splitted = hashTag.substr(1).split('/');
return { return {
route : splitted[0], route : splitted[0],
id : splitted[1], id : splitted[1],
method : splitted[2] method : splitted[2]
} }
}; };
$.extractAuth = function(hashTag){ $.extractAuth = function (hashTag) {
var del = hashTag.indexOf('&'); var del = hashTag.indexOf('&');
if( del != -1){ if (del != -1) {
var splitted = hashTag.substring(del+1).split('&'); var splitted = hashTag.substring(del+1).split('&');
var result = {}; var result = {};
for( p in splitted ){ for (p in splitted) {
var s = splitted[p].split('='); var s = splitted[p].split('=');
result[s[0]] = s[1]; result[s[0]] = s[1];
} }
return result; return result;
...@@ -35,29 +33,33 @@ $.extractAuth = function(hashTag){ ...@@ -35,29 +33,33 @@ $.extractAuth = function(hashTag){
return false; return false;
}; };
$.genHash = function(url){ $.genHash = function(url) {
if('id' in url){ url['id'] = '/' + url['id']; } if ('id' in url) {
if('method' in url){ url['method'] = '/' + url['method']; } url['id'] = '/' + url['id'];
return url['route'] + (url['id'] || '') + (url['method'] || ''); }
if ('method' in url) {
url['method'] = '/' + url['method'];
}
return '/' + url['route'] + (url['id'] || '') + (url['method'] || '');
}; };
/* Pub / Sub Pattern /* Pub / Sub Pattern
WARNING WARNING
What's happening when we destroy a DOM object subscribed ? What's happening when we destroy a DOM object subscribed ?
*/ */
var o = $({}); var o = $({});
$.subscribe = function() { $.subscribe = function() {
o.on.apply(o, arguments); o.on.apply(o, arguments);
}; };
$.unsubscribe = function() { $.unsubscribe = function() {
o.off.apply(o, arguments); o.off.apply(o, arguments);
}; };
$.publish = function() { $.publish = function() {
o.trigger.apply(o, arguments); o.trigger.apply(o, arguments);
}; };
// Event Handlers // Event Handlers
$.hashHandler = function(){ $.publish("urlChange", $.parseHash(window.location.hash)); }; $.hashHandler = function(){ $.publish("urlChange", window.location.hash.substr(1)); };
$.redirectHandler = function(event, url){ window.location.hash = $.genHash(url); }; $.redirectHandler = function(event, url){ window.location.hash = $.genHash(url); };
// redirections manager // redirections manager
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment