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 = {
init: function( options ){
init: function (options) {
var settings = $.extend({
'host': '',
'access_token': '',
'clientID': ''
}, options);
return this.each(function(){
methods['store'] = Modernizr.localstorage ? methods.lStore : methods.cStore;
for(var setting in settings){
return this.each(function () {
var setting;
methods.store = Modernizr.localstorage ? methods.lStore : methods.cStore;
for (setting in settings) {
if (settings.hasOwnProperty(setting)) {
$(this).slapos('store', setting, settings[setting]);
}
}
});
},
/* Getters & Setters shortcuts */
access_token: function( value ){
access_token: function (value) {
return $(this).slapos('store', 'access_token', value);
},
host: function( value ){
host: function (value) {
return $(this).slapos('store', 'host', value);
},
clientID: function( value ){
clientID: function (value) {
return $(this).slapos('store', 'clientID', value);
},
/* Local storage method */
lStore: function( name, value ) {
if(Modernizr.localstorage)
return value == undefined ? window.localStorage[name] : window.localStorage[name] = value;
lStore: function (name, value) {
if (Modernizr.localstorage) {
return value === undefined ? window.localStorage[name] : window.localStorage[name] = value;
}
return false;
},
/* Cookie storage method */
cStore: function(name, value){
if(value != undefined){
document.cookie = name+"="+value+";domain="+window.location.hostname+";path="+window.location.pathname;
}else{
var i,x,y, cookies = document.cookie.split(';');
for(i=0; i<cookies.length; i++){
cStore: function (name, value) {
if (value !== undefined) {
document.cookie = name + "=" + value + ";domain=" + window.location.hostname + ";path=" + window.location.pathname;
} else {
var i, x, y, cookies = document.cookie.split(';');
for (i = 0; i < cookies.length; i += 1) {
x = cookies[i].substr(0, cookies[i].indexOf('='));
y = cookies[i].substr(cookies[i].indexOf('=')+1);
x=x.replace(/^\s+|\s+$/g,"");
if(x == name) return unescape(y);
y = cookies[i].substr(cookies[i].indexOf('=') + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x === name) {
return unescape(y);
}
}
}
},
statusDefault: function(){
statusDefault: function () {
return {
0: function(){ console.error("status error code: 0"); },
404: function(){ console.error("status error code: Not Found !"); }
}
0: function () { console.error("status error code: 0"); },
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 || '';
statusEvent = statusEvent || this.statusDefault;
return this.each(function(){
statusCode = statusCode || this.statusDefault;
return this.each(function () {
$.ajax({
url: $(this).slapos('host')+url,
url: $(this).slapos('host') + url,
type: type,
contentType: 'application/octet-stream',
data: JSON.stringify(data),
dataType: 'json',
context: $(this),
beforeSend: function(xhr){
if( $(this).slapos("access_token") ) {
xhr.setRequestHeader("Authorization", $(this).slapos("store","token_type") + " " + $(this).slapos("access_token"));
beforeSend: function (xhr) {
if ($(this).slapos("access_token")) {
xhr.setRequestHeader("Authorization", $(this).slapos("store", "token_type") + " " + $(this).slapos("access_token"));
xhr.setRequestHeader("Accept", "application/json");
}
},
statusCode: statusEvent,
statusCode: statusCode,
success: callback
});
});
},
newInstance: function(data, callback, statusEvent){
newInstance: function (data, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/instance', callback, statusEvent, data);
},
deleteInstance: function(id, callback, statusEvent){
return $(this).slapos('request', 'DELETE', '/instance/'+id, callback, statusEvent);
deleteInstance: function (id, callback, statusEvent) {
return $(this).slapos('request', 'DELETE', '/instance/' + id, callback, statusEvent);
},
getInstance: function(id, callback, statusEvent){
return $(this).slapos('request', 'GET', '/instance/'+id, callback, statusEvent);
getInstance: function (id, callback, statusEvent) {
return $(this).slapos('request', 'GET', '/instance/' + id, callback, statusEvent);
},
getInstanceCert: function(id, callback, statusEvent){
return $(this).slapos('request', 'GET', '/instance/'+id+'/certificate', callback, statusEvent);
getInstanceCert: function (id, callback, statusEvent) {
return $(this).slapos('request', 'GET', '/instance/' + id + '/certificate', callback, statusEvent);
},
bangInstance: function(id, log, callback, statusEvent){
return $(this).slapos('request', 'POST', '/instance/'+id+'/bang', callback, statusEvent, log);
bangInstance: function (id, log, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/instance/' + id + '/bang', callback, statusEvent, log);
},
editInstance: function(id, data, callback, statusEvent){
return $(this).slapos('request', 'PUT', '/instance/'+id, callback, statusEvent, data);
editInstance: function (id, data, callback, statusEvent) {
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);
},
getComputer: function(id, callback, statusEvent){
return $(this).slapos('request', 'GET', '/computer/'+id, callback, statusEvent);
getComputer: function (id, callback, statusEvent) {
return $(this).slapos('request', 'GET', '/computer/' + id, callback, statusEvent);
},
editComputer: function(id, data, callback, statusEvent){
return $(this).slapos('request', 'PUT', '/computer/'+id, callback, statusEvent, data);
editComputer: function (id, data, callback, statusEvent) {
return $(this).slapos('request', 'PUT', '/computer/' + id, callback, statusEvent, data);
},
newSoftware: function(computerId, data, callback, statusEvent){
return $(this).slapos('request', 'POST', '/computer/'+computerId+'/supply', callback, statusEvent, data);
newSoftware: function (computerId, data, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/computer/' + computerId + '/supply', callback, statusEvent, data);
},
bangComputer: function(id, log, callback, statusEvent){
return $(this).slapos('request', 'POST', '/computer/'+id+'/bang', callback, statusEvent, log);
bangComputer: function (id, log, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/computer/' + id + '/bang', callback, statusEvent, log);
},
computerReport: function(id, data, callback, statusEvent){
return $(this).slapos('request', 'POST', '/computer/'+id+'/report', callback, statusEvent, data);
computerReport: function (id, data, callback, statusEvent) {
return $(this).slapos('request', 'POST', '/computer/' + id + '/report', callback, statusEvent, data);
}
};
$.fn.slapos = function(method){
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
$.fn.slapos = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.slapos' );
$.error('Method ' + method + ' does not exist on jQuery.slapos');
}
};
})(jQuery);
......@@ -157,7 +157,7 @@
<li><a href="#"><i class="icon-star"></i>Favorites</a></li>
<li class="nav-header">Services</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>
<ul style="list-style: none">
<li><a href="#service/200"><i class="icon-"></i>inst-0</a></li>
......
......@@ -68,17 +68,17 @@ var inst1 =
tap_interface: "tap2"}
};
/*var fakeserver = sinon.fakeServer.create();
var fakeserver = sinon.fakeServer.create();
// 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)]);
// Get instance FAIL
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;
/*$.ajax = function(url, options){
$.ajax = function(url, options){
var result = tmp(url, options);
fakeserver.respond();
return result;
......
......@@ -3,18 +3,34 @@
* Author: Thomas Lechauve
* 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 = {
init: function() {
// Initialize slapos in this context
$(this).slapos({host: '10.0.1.139:12002/erp5/portal_vifib_rest_api_v1'});
var $this = $(this);
// Bind to urlChange event
return this.each(function(){
var self = $(this);
$.subscribe("urlChange", function(e, d){
if(d.route == "service" && d.id) { self.form('displayData', d.id); }
else if(d.route == "service") { self.form('displayForm'); }
router.call($this, e, d);
});
$.subscribe("auth", function(e, d){
$(this).form("authenticate", d);
......@@ -22,23 +38,29 @@
});
},
authenticate: function(data){
for(var d in data){
authenticate: function(data) {
for (var d in data) {
if (data.hasOwnProperty(d)) {
$(this).slapos('store', d, data[d]);
}
}
},
displayData: function(id){
$(this).html("<p>Ajax loading...</p>")
.slapos('getInstance', id, function(data){
$(this).form('render', 'service', data);
}, {401: function(){
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>")
.slapos('getInstance', id, function(data){
$(this).form('render', 'service', data);
}, statusCode);
},
displayForm: function() {
......@@ -67,17 +89,22 @@
computer_id: "COMP-0",
}
};
$.extend(request, data);
$(this).html("<p>Requesting a new instance "+request["title"]+" ...</p>")
.slapos('newInstance', request, function(data){
$(this).html(data);}, {401: function(){
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);
$(this).html("<p>Requesting a new instance "+request["title"]+" ...</p>")
.slapos('newInstance', request, function(data){
$(this).html(data);},
statusCode
);
},
render: function(template, data){
......
......@@ -4,12 +4,11 @@
* Date: 4/18/12
*/
;
// Hash parser utility
$.parseHash = function(hashTag){
$.parseHash = function(hashTag) {
var tokenized = $.extractAuth(hashTag);
if( tokenized ){
console.log(tokenized);
if (tokenized) {
$.publish('auth', tokenized);
}
var splitted = hashTag.substr(1).split('/');
......@@ -20,14 +19,13 @@ $.parseHash = function(hashTag){
}
};
$.extractAuth = function(hashTag){
$.extractAuth = function (hashTag) {
var del = hashTag.indexOf('&');
if( del != -1){
if (del != -1) {
var splitted = hashTag.substring(del+1).split('&');
var result = {};
for( p in splitted ){
for (p in splitted) {
var s = splitted[p].split('=');
result[s[0]] = s[1];
}
return result;
......@@ -35,10 +33,14 @@ $.extractAuth = function(hashTag){
return false;
};
$.genHash = function(url){
if('id' in url){ url['id'] = '/' + url['id']; }
if('method' in url){ url['method'] = '/' + url['method']; }
return url['route'] + (url['id'] || '') + (url['method'] || '');
$.genHash = function(url) {
if ('id' in url) {
url['id'] = '/' + url['id'];
}
if ('method' in url) {
url['method'] = '/' + url['method'];
}
return '/' + url['route'] + (url['id'] || '') + (url['method'] || '');
};
/* Pub / Sub Pattern
......@@ -57,7 +59,7 @@ $.publish = function() {
};
// 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); };
// 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