add raw error dialog support, only add model to collection once it has been saved
[plstackapi.git] / planetstack / core / xoslib / static / js / xoslib / xos-backbone.js
index 8770797..918e4a2 100644 (file)
@@ -3,8 +3,6 @@ if (! window.XOSLIB_LOADED ) {
 
     SLIVER_API = "/plstackapi/slivers/";
     SLICE_API = "/plstackapi/slices/";
-    SLICEDEPLOYMENT_API = "/plstackapi/slice_deployments/";
-    SLICEPRIVILEGE_API = "/plstackapi/slice_privileges/";
     SLICEROLE_API = "/plstackapi/slice_roles/";
     NODE_API = "/plstackapi/nodes/";
     SITE_API = "/plstackapi/sites/";
@@ -13,10 +11,19 @@ if (! window.XOSLIB_LOADED ) {
     DEPLOYMENT_API = "/plstackapi/deployments/";
     IMAGE_API = "/plstackapi/images/";
     NETWORKTEMPLATE_API = "/plstackapi/networktemplates/";
-    NETWORKDEPLOYMENT_API = "/plstackapi/networkdeployments/";
     NETWORK_API = "/plstackapi/networks/";
     NETWORKSLIVER_API = "/plstackapi/networkslivers/";
     SERVICE_API = "/plstackapi/services/";
+    SLICEPRIVILEGE_API = "/plstackapi/slice_privileges/";
+    NETWORKDEPLOYMENT_API = "/plstackapi/networkdeployments/";
+
+    /* changed as a side effect of the big rename
+    SLICEDEPLOYMENT_API = "/plstackapi/slice_deployments/";
+    USERDEPLOYMENT_API = "/plstackapi/user_deployments/";
+    */
+
+    SLICEDEPLOYMENT_API = "/plstackapi/slicedeployments/";
+    USERDEPLOYMENT_API = "/plstackapi/userdeployments/";
 
     SLICEPLUS_API = "/xoslib/slicesplus/";
 
@@ -29,7 +36,12 @@ if (! window.XOSLIB_LOADED ) {
                     var url = this.attributes.resource_uri;
 
                     if (!url) {
-                        url = this.urlRoot + this.id;
+                        if (this.id) {
+                            url = this.urlRoot + this.id;
+                        } else {
+                            // this happens when creating a new model.
+                            url = this.urlRoot;
+                        }
                     }
 
                     if (!url) {
@@ -56,6 +68,26 @@ if (! window.XOSLIB_LOADED ) {
                     }\r
                 }\r
                 return res;\r
+            },
+
+            xosValidate: function(attrs, options) {
+                errors = {};
+                foundErrors = false;
+                _.each(this.validators, function(validatorList, fieldName) {
+                    _.each(validatorList, function(validator) {
+                        if (fieldName in attrs) {
+                            validatorResult = validateField(validator, attrs[fieldName], this)
+                            if (validatorResult != true) {
+                                errors[fieldName] = validatorResult;
+                                foundErrors = true;
+                            }
+                        }
+                    });
+                });
+                if (foundErrors) {
+                    return errors;
+                }
+                // backbone.js semantics -- on successful validate, return nothing
             }
     });
 
@@ -66,6 +98,8 @@ if (! window.XOSLIB_LOADED ) {
 
         initialize: function(){
           this.isLoaded = false;
+          this.failedLoad = false;
+          this.startedLoad = false;
           this.sortVar = 'name';\r
           this.sortOrder = 'asc';\r
           this.on( "sort", this.sorted );\r
@@ -75,7 +109,7 @@ if (! window.XOSLIB_LOADED ) {
         foreignCollections: [],\r
 \r
         sorted: function() {\r
-            this.isLoaded = true;\r
+            //console.log("sorted " + this.modelName);\r
         },\r
 \r
         simpleComparator: function( model ){\r
@@ -101,6 +135,52 @@ if (! window.XOSLIB_LOADED ) {
             }\r
         },\r
 \r
+        fetchSuccess: function(collection, response, options) {\r
+            //console.log("fetch succeeded " + collection.modelName);\r
+            this.failedLoad = false;\r
+            this.fetching = false;\r
+            if (!this.isLoaded) {\r
+                this.isLoaded = true;\r
+                Backbone.trigger("xoslib:collectionLoadChange", this);\r
+            }\r
+            this.trigger("fetchStateChange");\r
+            if (options["orig_success"]) {\r
+                options["orig_success"](collection, response, options);\r
+            }\r
+        },\r
+\r
+        fetchFailure: function(collection, response, options) {\r
+            //console.log("fetch failed " + collection.modelName);\r
+            this.fetching = false;\r
+            if ((!this.isLoaded) && (!this.failedLoad)) {\r
+                this.failedLoad=true;\r
+                Backbone.trigger("xoslib:collectionLoadChange", this);\r
+            }\r
+            this.trigger("fetchStateChange");\r
+            if (options["orig_failure"]) {\r
+                options["orig_failure"](collection, response, options);\r
+            }\r
+        },\r
+\r
+        fetch: function(options) {\r
+            var self=this;\r
+            this.fetching=true;\r
+            //console.log("fetch " + this.modelName);\r
+            if (!this.startedLoad) {\r
+                this.startedLoad=true;\r
+                Backbone.trigger("xoslib:collectionLoadChange", this);\r
+            }\r
+            this.trigger("fetchStateChange");\r
+            if (options == undefined) {\r
+                options = {};\r
+            }\r
+            options["orig_success"] = options["success"];\r
+            options["orig_failure"] = options["failure"];\r
+            options["success"] = function(collection, response, options) { self.fetchSuccess.call(self, collection, response, options); };\r
+            options["failure"] = this.fetchFailure;\r
+            Backbone.Collection.prototype.fetch.call(this, options);\r
+        },\r
+\r
         startPolling: function() {\r
             if (!this._polling) {\r
                 var collection=this;
@@ -110,6 +190,20 @@ if (! window.XOSLIB_LOADED ) {
             }
         },
 
+        refresh: function(refreshRelated) {
+            if (!this.fetching) {
+                this.fetch();
+            }
+            if (refreshRelated) {
+                for (related in this.relatedCollections) {
+                    related = xos[related];
+                    if (!related.fetching) {
+                        related.fetch();
+                    }
+                }
+            }
+        },
+
         maybeFetch: function(options){
                 // Helper function to fetch only if this collection has not been fetched before.
             if(this._fetched){
@@ -186,109 +280,154 @@ if (! window.XOSLIB_LOADED ) {
             },
     });
 
+    function define_model(lib, attrs) {
+        modelName = attrs.modelName;
+        modelClassName = modelName;
+        collectionClassName = modelName + "Collection";
+
+        if (!attrs.collectionName) {
+            attrs.collectionName = modelName + "s";
+        }
+        collectionName = attrs.collectionName;
+
+        modelAttrs = {}
+        collectionAttrs = {}
+
+        for (key in attrs) {
+            value = attrs[key];
+            if ($.inArray(key, ["urlRoot", "modelName", "validate"])>=0) {
+                modelAttrs[key] = value;
+            }
+            if ($.inArray(key, ["urlRoot", "modelName", "relatedCollections", "foreignCollections"])>=0) {
+                collectionAttrs[key] = value;
+            }
+        }
+
+        if (xosdefaults && xosdefaults[modelName]) {
+            modelAttrs["defaults"] = xosdefaults[modelName];
+        }
+
+        if (xosvalidators && xosvalidators[modelName]) {
+            modelAttrs["validators"] = xosvalidators[modelName];
+        }
+
+        lib[modelName] = XOSModel.extend(modelAttrs);
+
+        collectionAttrs["model"] = lib[modelName];
+
+        lib[collectionClassName] = XOSCollection.extend(collectionAttrs);
+        lib[collectionName] = new lib[collectionClassName]();
+
+        lib.allCollectionNames.push(collectionName);
+        lib.allCollections.push(lib[collectionName]);
+    };
+
     function xoslib() {
-        // basic REST
-        this.sliver = XOSModel.extend({ urlRoot: SLIVER_API, modelName: "sliver" });
-        this.sliverCollection = XOSCollection.extend({ urlRoot: SLIVER_API,
-                                                       relatedCollections: {"networkSlivers": "sliver"},
-                                                       foreignCollections: ["slices", "deployments", "images", "nodes", "users"],
-                                                       model: this.sliver});
-        this.slivers = new this.sliverCollection();
-
-        this.slice = XOSModel.extend({ urlRoot: SLICE_API, modelName: "slice" });
-        this.sliceCollection = XOSCollection.extend({ urlRoot: SLICE_API,
-                                                       relatedCollections: {"slivers": "slice", "sliceDeployments": "slice", "slicePrivileges": "slice", "networks": "owner"},
-                                                       foreignCollections: ["services", "sites"],
-                                                       model: this.slice});
-        this.slices = new this.sliceCollection();
-
-        this.sliceDeployment = XOSModel.extend({ urlRoot: SLICEDEPLOYMENT_API, modelName: "sliceDeployment" });
-        this.sliceDeploymentCollection = XOSCollection.extend({ urlRoot: SLICEDEPLOYMENT_API,
-                                                       foreignCollections: ["slices", "deployments"],
-                                                       model: this.slice});
-        this.sliceDeployments = new this.sliceDeploymentCollection();
-
-        this.slicePrivilege = XOSModel.extend({ urlRoot: SLICEPRIVILEGE_API, modelName: "slicePrivilege" });
-        this.slicePrivilegeCollection = XOSCollection.extend({ urlRoot: SLICEPRIVILEGE_API,
-                                                       foreignCollections: ["slices", "users", "sliceRoles"],
-                                                       model: this.slice});
-        this.slicePrivileges = new this.slicePrivilegeCollection();
-
-        this.sliceRole = XOSModel.extend({ urlRoot: SLICEROLE_API, modelName: "sliceRole" });
-        this.sliceRoleCollection = XOSCollection.extend({ urlRoot: SLICEROLE_API,
-                                                       model: this.slice});
-        this.sliceRoles = new this.sliceRoleCollection();
-
-        this.node = XOSModel.extend({ urlRoot: NODE_API, modelName: "node" });
-        this.nodeCollection = XOSCollection.extend({ urlRoot: NODE_API,
-                                                       foreignCollections: ["sites", "deployments"],
-                                                       model: this.node});
-        this.nodes = new this.nodeCollection();
-
-        this.site = XOSModel.extend({ urlRoot: SITE_API, modelName: "site" });
-        this.siteCollection = XOSCollection.extend({ urlRoot: SITE_API,
-                                                       model: this.site});
-        this.sites = new this.siteCollection();
-
-        this.user = XOSModel.extend({ urlRoot: USER_API, modelName: "user" });
-        this.userCollection = XOSCollection.extend({ urlRoot: USER_API,
-                                                       relatedCollections: {"slicePrivileges": "user", "slices": "owner", "userDeployments": "user"},
-                                                       foreignCollections: ["sites"],
-                                                       model: this.user});
-        this.users = new this.userCollection();
-
-        this.userDeployment = XOSModel.extend({ urlRoot: USERDEPLOYMENT_API, modelName: "userDeployment" });
-        this.userDeploymentCollection = XOSCollection.extend({ urlRoot: USERDEPLOYMENT_API,
-                                                       foreignCollections: ["users","deployments"],
-                                                       model: this.user});
-        this.userDeployments = new this.userDeploymentCollection();
-
-        this.deployment = XOSModel.extend({ urlRoot: DEPLOYMENT_API, modelName: "deployment" });
-        this.deploymentCollection = XOSCollection.extend({ urlRoot: DEPLOYMENT_API,
-                                                           relatedCollections: {"slivers": "deploymentNetwork", "networkDeployments": "deployment", "userDeployments": "deployment"},
-                                                           model: this.deployment});
-        this.deployments = new this.deploymentCollection();
-
-        this.image = XOSModel.extend({ urlRoot: IMAGE_API, modelName: "image" });
-        this.imageCollection = XOSCollection.extend({ urlRoot: IMAGE_API,
-                                                           model: this.image});
-        this.images = new this.imageCollection();
-
-        this.networkTemplate = XOSModel.extend({ urlRoot: NETWORKTEMPLATE_API, modelName: "networkTemplate" });
-        this.networkTemplateCollection = XOSCollection.extend({ urlRoot: NETWORKTEMPLATE_API,
-                                                           model: this.networkTemplate});
-        this.networkTemplates = new this.networkTemplateCollection();
-
-        this.network = XOSModel.extend({ urlRoot: NETWORK_API, modelName: "network" });
-        this.networkCollection = XOSCollection.extend({ urlRoot: NETWORK_API,
-                                                           relatedCollections: {"networkDeployments": "network", "networkSlivers": "network"},
-                                                           foreignCollections: ["slices", "networkTemplates"],
-                                                           model: this.network});
-        this.networks = new this.networkCollection();
-
-        this.networkSliver = XOSModel.extend({ urlRoot: NETWORKSLIVER_API, modelName: "networkSliver" });
-        this.networkSliverCollection = XOSCollection.extend({ urlRoot: NETWORKSLIVER_API,
-                                                           model: this.networkSliver});
-        this.networkSlivers = new this.networkSliverCollection();
-
-        this.networkDeployment = XOSModel.extend({ urlRoot: NETWORKDEPLOYMENT_API, modelName: "networkDeployment" });
-        this.networkDeploymentCollection = XOSCollection.extend({ urlRoot: NETWORKDEPLOYMENT_API,
-                                                           model: this.networkDeployment});
-        this.networkDeployments = new this.networkDeploymentCollection();
-
-        this.service = XOSModel.extend({ urlRoot: SERVICE_API, modelName: "sliver" });
-        this.serviceCollection = XOSCollection.extend({ urlRoot: SERVICE_API,
-                                                       model: this.service});
-        this.services = new this.serviceCollection();
+        this.allCollectionNames = [];
+        this.allCollections = [];
+
+        define_model(this, {urlRoot: SLIVER_API,
+                            relatedCollections: {"networkSlivers": "sliver"},
+                            foreignCollections: ["slices", "deployments", "images", "nodes", "users"],
+                            modelName: "sliver"});
+
+        define_model(this, {urlRoot: SLICE_API,
+                           relatedCollections: {"slivers": "slice", "sliceDeployments": "slice", "slicePrivileges": "slice", "networks": "owner"},
+                           foreignCollections: ["services", "sites"],
+                           modelName: "slice",
+                           validate: function(attrs, options) {
+                               errors = XOSModel.prototype.validate(this, attrs, options);
+                               // validate that slice.name starts with site.login_base
+                               site = attrs.site || this.site;
+                               if ((site!=undefined) && (attrs.name!=undefined)) {
+                                   site = xos.sites.get(site);
+                                   if (attrs.name.indexOf(site.attributes.login_base+"_") != 0) {
+                                        errors = errors || {};
+                                        errors["name"] = "must start with " + site.attributes.login_base + "_";
+                                   }
+                               }
+                               return errors;
+                             },
+                           });
+
+        define_model(this, {urlRoot: SLICEDEPLOYMENT_API,
+                           foreignCollections: ["slices", "deployments"],
+                           modelName: "sliceDeployment"});
+
+        define_model(this, {urlRoot: SLICEPRIVILEGE_API,
+                            foreignCollections: ["slices", "users", "sliceRoles"],
+                            modelName: "slicePrivilege"});
+
+        define_model(this, {urlRoot: SLICEROLE_API,
+                            modelName: "sliceRole"});
+
+        define_model(this, {urlRoot: NODE_API,
+                            foreignCollections: ["sites", "deployments"],
+                            modelName: "node"});
+
+        define_model(this, {urlRoot: SITE_API,
+                            relatedCollections: {"users": "site", "slices": "site", "nodes": "site"},
+                            modelName: "site"});
+
+        define_model(this, {urlRoot: USER_API,
+                            relatedCollections: {"slicePrivileges": "user", "slices": "owner", "userDeployments": "user"},
+                            foreignCollections: ["sites"],
+                            modelName: "user"});
+
+        define_model(this, {urlRoot: USERDEPLOYMENT_API,
+                            foreignCollections: ["users","deployments"],
+                            modelName: "userDeployment"});
+
+        define_model(this, { urlRoot: DEPLOYMENT_API,
+                             relatedCollections: {"nodes": "deployment", "slivers": "deploymentNetwork", "networkDeployments": "deployment", "userDeployments": "deployment"},
+                             modelName: "deployment"});
+
+        define_model(this, {urlRoot: IMAGE_API,
+                            model: this.image,
+                            modelName: "image"});
+
+        define_model(this, {urlRoot: NETWORKTEMPLATE_API,
+                            modelName: "networkTemplate"});
+
+        define_model(this, {urlRoot: NETWORK_API,
+                            relatedCollections: {"networkDeployments": "network", "networkSlivers": "network"},
+                            foreignCollections: ["slices", "networkTemplates"],
+                            modelName: "network"});
+
+        define_model(this, {urlRoot: NETWORKSLIVER_API,
+                            modelName: "networkSliver"});
+
+        define_model(this, {urlRoot: NETWORKDEPLOYMENT_API,
+                            modelName: "networkDeployment"});
+
+        define_model(this, {urlRoot: SERVICE_API,
+                            modelName: "service"});
 
         // enhanced REST
-        this.slicePlus = XOSModel.extend({ urlRoot: SLICEPLUS_API, modelName: "slicePlus" });
-        this.slicePlusCollection = XOSCollection.extend({ urlRoot: SLICEPLUS_API,
-                                                          relatedCollections: {'slivers': "slice"},
-                                                          model: this.slicePlus});
-        this.slicesPlus = new this.slicePlusCollection();
-
-        this.listObjects = function() { return ["slivers", "slices", "nodes", "sites", "users", "deployments"]; };
+        define_model(this, {urlRoot: SLICEPLUS_API,
+                            relatedCollections: {'slivers': "slice"},
+                            modelName: "slicePlus",
+                            collectionName: "slicesPlus"});
+
+        this.listObjects = function() { return this.allCollectionNames; };
+
+        this.getCollectionStatus = function() {
+            stats = {isLoaded: 0, failedLoad: 0, startedLoad: 0};
+            for (index in this.allCollections) {
+                collection = this.allCollections[index];
+                if (collection.isLoaded) {
+                    stats["isLoaded"] = stats["isLoaded"] + 1;
+                }
+                if (collection.failedLoad) {
+                    stats["failedLoad"] = stats["failedLoad"] + 1;
+                }
+                if (collection.startedLoad) {
+                    stats["startedLoad"] = stats["startedLoad"] + 1;
+                }
+            }
+            stats["completedLoad"] = stats["failedLoad"] + stats["isLoaded"];
+            return stats;
+        };
     };
 
     xos = new xoslib();