baas.io Javascript SDK v0.9.2 src/entity/entity.js

Entity

method
Baas.Entity()

    Description

    A class to Model a Baas Entity.
    Set the type of entity in the 'data' json object

    @constructor
    @param {object} options {client:client, data:{'type':'collection_type', 'key':'value'}, uuid:uuid}}

    Source

    Baas.Entity = function(options) {
    	if(options){
    	  this._client = options.client;
    	  this._data = options.data || {};
    	}
      };

    serialize

    method
    Baas.Entity.prototype.serialize()

      Description

      returns a serialized version of the entity object

      Note: use the client.restoreEntity() function to restore

      @method serialize
      @return {string} data

      Source

      Baas.Entity.prototype.serialize = function () {
      	return JSON.stringify(this._data);
        }

      get

      method
      Baas.Entity.prototype.get()

        Description

        gets a specific field or the entire data object. If null or no argument
        passed, will return all data, else, will return a specific field

        @method get
        @param {string} field
        @return {string} || {object} data

        Source

        Baas.Entity.prototype.get = function (field) {
        	if (field) {
        	  return this._data[field];
        	} else {
        	  return this._data;
        	}
          }

        set

        method
        Baas.Entity.prototype.set()

          Description

          adds a specific key value pair or object to the Entity's data
          is additive - will not overwrite existing values unless they
          are explicitly specified

          @method set
          @param {string} key || {object}
          @param {string} value
          @return none

          Source

          Baas.Entity.prototype.set = function (key, value) {
          	if (typeof key === 'object') {
          	  for(var field in key) {
          		this._data[field] = key[field];
          	  }
          	} else if (typeof key === 'string') {
          	  if (value === null) {
          		delete this._data[key];
          	  } else {
          		this._data[key] = value;
          	  }
          	} else {
          	  this._data = null;
          	}
            }

          save

          method
          Baas.Entity.prototype.save()

            Description

            Saves the entity back to the database

            @method save
            @public
            @param {function} callback
            @return {callback} callback(err, data)

            Source

            Baas.Entity.prototype.save = function (callback) {
            	//TODO:  API will be changed soon to accomodate PUTs via name which create new entities
            	//       This function should be changed to PUT only at that time, and updated to use
            	//       either uuid or name
            	var type = this.get('type');
            	var method = 'POST';
            	if (Baas.Utils.isUUID(this.get('uuid'))) {
            	  method = 'PUT';
            	  type += '/' + this.get('uuid');
            	} else if(type === 'users' && this.get('username')) {
            	  method = 'PUT';
            	  type += '/' + this.get('username');
            	} else if(this.get('name')){
            	   method = 'PUT';
            	  type += '/' + this.get('name');
            	}
            
            	//update the entity
            	var self = this;
            	var data = {};
            	var entityData = this.get();
            	//remove system specific properties
            	for (var item in entityData) {
            	  if (item === 'metadata' || item === 'created' || item === 'modified' ||
            		  item === 'type' || item === 'activated' || item ==='uuid') { continue; }
            	  data[item] = entityData[item];
            	}
            	var options =  {
            	  method:method,
            	  endpoint:type,
            	  body:data
            	};
            	//save the entity first
            	this._client.request(options, function (err, retdata) {
            	  if (err && self._client.logging) {
            		console.log('could not save entity');
            		if (typeof(callback) === 'function') {
            		  return callback(err, retdata, self);
            		}
            	  } else {
            		if (retdata.entities) {
            		  if (retdata.entities.length) {
            			var entity = retdata.entities[0];
            			self.set(entity);
            		  }
            		}
            		//if this is a user, update the password if it has been specified;
            		var needPasswordChange = (self.get('type') === 'user' && entityData.oldpassword && entityData.newpassword);
            		if (needPasswordChange) {
            		  //Note: we have a ticket in to change PUT calls to /users to accept the password change
            		  //      once that is done, we will remove this call and merge it all into one
            		  var pwdata = {};
            		  pwdata.oldpassword = entityData.oldpassword;
            		  pwdata.newpassword = entityData.newpassword;
            		  var options = {
            			method:'PUT',
            			endpoint:type+'/password',
            			body:pwdata
            		  }
            		  self._client.request(options, function (err, data) {
            			if (err && self._client.logging) {
            			  console.log('could not update user');
            			}
            			//remove old and new password fields so they don't end up as part of the entity object
            			self.set('oldpassword', null);
            			self.set('newpassword', null);
            			if (typeof(callback) === 'function') {
            			  callback(err, data, self);
            			}
            		  });
            		} else if (typeof(callback) === 'function') {
            		  callback(err, retdata, self);
            		}
            	  }
            	});
              }

            fetch

            method
            Baas.Entity.prototype.fetch()

              Description

              refreshes the entity by making a GET call back to the database

              @method fetch
              @public
              @param {function} callback
              @return {callback} callback(err, data)

              Source

              Baas.Entity.prototype.fetch = function (callback) {
              	var type = this.get('type');
              	var self = this;
              
              	//if a uuid is available, use that, otherwise, use the name
              	if (this.get('uuid')) {
              	  type += '/' + this.get('uuid');
              	} else {
              	  if (type === 'users') {
              		if (this.get('username')) {
              		  type += '/' + this.get('username');
              		} else {
              		  if (typeof(callback) === 'function') {
              			var error = 'no_name_specified';
              			if (self._client.logging) {
              			  console.log(error);
              			}
              			return callback(true, {error:error}, self)
              		  }
              		}
              	  } else if (type === 'a path') {
              
              		///TODO add code to deal with the type as a path
              
              		if (this.get('path')) {
              		  type += '/' + encodeURIComponent(this.get('name'));
              		} else {
              		  if (typeof(callback) === 'function') {
              			var error = 'no_name_specified';
              			if (self._client.logging) {
              			  console.log(error);
              			}
              			return callback(true, {error:error}, self)
              		  }
              		}
              
              	  } else {
              		if (this.get('name')) {
              		  type += '/' + encodeURIComponent(this.get('name'));
              		} else {
              		  if (typeof(callback) === 'function') {
              			var error = 'no_name_specified';
              			if (self._client.logging) {
              			  console.log(error);
              			}
              			return callback(true, {error:error}, self)
              		  }
              		}
              	  }
              	}
              	var options = {
              	  method:'GET',
              	  endpoint:type
              	};
              	this._client.request(options, function (err, data) {
              	  if (err && self._client.logging) {
              		console.log('could not get entity');
              	  } else {
              		if (data.user) {
              		  self.set(data.user);
              		  self._json = JSON.stringify(data.user, null, 2);
              		} else if (data.entities) {
              		  if (data.entities.length) {
              			var entity = data.entities[0];
              			self.set(entity);
              		  }
              		}
              	  }
              	  if (typeof(callback) === 'function') {
              		callback(err, data, self);
              	  }
              	});
                }

              destroy

              method
              Baas.Entity.prototype.destroy()

                Description

                deletes the entity from the database - will only delete
                if the object has a valid uuid

                @method destroy
                @public
                @param {function} callback
                @return {callback} callback(err, data)

                Source

                Baas.Entity.prototype.destroy = function (callback) {
                
                		var type = this.get('type');
                
                		if (Baas.Utils.isUUID(this.get('uuid'))) {
                			type += '/' + this.get('uuid');
                		} else {
                
                			if (type === 'users') {
                				if (this.get('username')) {
                					type += '/' + this.get('username');
                				} else {
                					if (typeof(callback) === 'function') {
                						var error = 'Error trying to delete object - no uuid specified.';
                						if (self._client.logging) {
                							console.log(error);
                						}
                						callback(true, error);
                					}
                				}
                			} else {
                				if(this.get('name')) {
                					type += '/' + this.get('name');
                				} else {
                					if (typeof(callback) === 'function') {
                						var error = 'Error trying to delete object - no uuid specified.';
                						if (self._client.logging) {
                							console.log(error);
                						}
                						callback(true, error);
                					}
                				}
                			} 
                		} 
                
                		var self = this;
                		var options = {
                			method:'DELETE',
                			endpoint:type
                		};
                
                		this._client.request(options, function (err, data) {
                			if (err && self._client.logging) {
                				console.log('entity could not be deleted');
                			} else {
                				self.set(null);
                			}
                
                			if (typeof(callback) === 'function') {
                				callback(err, data);
                			}
                		});
                	}

                connect

                method
                Baas.Entity.prototype.connect()

                  Description

                  connects one entity to another

                  @method connect
                  @public
                  @param {string} connection
                  @param {object} entity
                  @param {function} callback
                  @return {callback} callback(err, data)

                  Source

                  Baas.Entity.prototype.connect = function (connection, entity, callback) {
                  
                  	var self = this;
                  
                  	//connectee info
                  	var connecteeType = entity.get('type');
                  	var connectee = this.getEntityId(entity);
                  	if (!connectee) {
                  	  if (typeof(callback) === 'function') {
                  		var error = 'Error trying to delete object - no uuid specified.';
                  		if (self._client.logging) {
                  		  console.log(error);
                  		}
                  		callback(true, error);
                  	  }
                  	  return;
                  	}
                  
                  	//connector info
                  	var connectorType = this.get('type');
                  	var connector = this.getEntityId(this);
                  	if (!connector) {
                  	  if (typeof(callback) === 'function') {
                  		var error = 'Error in connect - no uuid specified.';
                  		if (self._client.logging) {
                  		  console.log(error);
                  		}
                  		callback(true, error);
                  	  }
                  	  return;
                  	}
                  
                  	var endpoint = connectorType + '/' + connector + '/' + connection + '/' + connecteeType + '/' + connectee;
                  	var options = {
                  	  method:'POST',
                  	  endpoint:endpoint
                  	};
                  	this._client.request(options, function (err, data) {
                  	  if (err && self._client.logging) {
                  		console.log('entity could not be connected');
                  	  }
                  	  if (typeof(callback) === 'function') {
                  		callback(err, data);
                  	  }
                  	});
                    }

                  getEntityId

                  method
                  Baas.Entity.prototype.getEntityId()

                    Description

                    returns a unique identifier for an entity

                    @method connect
                    @public
                    @param {object} entity
                    @param {function} callback
                    @return {callback} callback(err, data)

                    Source

                    Baas.Entity.prototype.getEntityId = function (entity) {
                    	var id = false;
                    	if (Baas.Utils.isUUID(entity.get('uuid'))) {
                    	  id = entity.get('uuid');
                    	} else {
                    	  if (type === 'users') {
                    		id = entity.get('username');
                    	  } else if (entity.get('name')) {
                    		id = entity.get('name');
                    	  }
                    	}
                    	return id;
                      }

                    getConnections

                    method
                    Baas.Entity.prototype.getConnections()

                      Description

                      gets an entities connections

                      @method getConnections
                      @public
                      @param {string} connection
                      @param {object} entity
                      @param {function} callback
                      @return {callback} callback(err, data, connections)

                      Source

                      Baas.Entity.prototype.getConnections = function (connection, callback) {
                      
                      	var self = this;
                      
                      	//connector info
                      	var connectorType = this.get('type');
                      	var connector = this.getEntityId(this);
                      	if (!connector) {
                      	  if (typeof(callback) === 'function') {
                      		var error = 'Error in getConnections - no uuid specified.';
                      		if (self._client.logging) {
                      		  console.log(error);
                      		}
                      		callback(true, error);
                      	  }
                      	  return;
                      	}
                      
                      	var endpoint = connectorType + '/' + connector + '/' + connection + '/';
                      	var options = {
                      	  method:'GET',
                      	  endpoint:endpoint
                      	};
                      	this._client.request(options, function (err, data) {
                      	  if (err && self._client.logging) {
                      		console.log('entity could not be connected');
                      	  }
                      
                      	  self[connection] = {};
                      
                      	  var length = data.entities.length;
                      	  for (var i=0;i<length;i++)
                      	  {
                      		if (data.entities[i].type === 'user'){
                      		  self[connection][data.entities[i].username] = data.entities[i];
                      		} else {
                      		  self[connection][data.entities[i].name] = data.entities[i]
                      		}
                      	  }
                      
                      	  if (typeof(callback) === 'function') {
                      		callback(err, data, data.entities);
                      	  }
                      	});
                      
                        }

                      disconnect

                      method
                      Baas.Entity.prototype.disconnect()

                        Description

                        disconnects one entity from another

                        @method disconnect
                        @public
                        @param {string} connection
                        @param {object} entity
                        @param {function} callback
                        @return {callback} callback(err, data)

                        Source

                        Baas.Entity.prototype.disconnect = function (connection, entity, callback) {
                        
                        	var self = this;
                        
                        	//connectee info
                        	var connecteeType = entity.get('type');
                        	var connectee = this.getEntityId(entity);
                        	if (!connectee) {
                        	  if (typeof(callback) === 'function') {
                        		var error = 'Error trying to delete object - no uuid specified.';
                        		if (self._client.logging) {
                        		  console.log(error);
                        		}
                        		callback(true, error);
                        	  }
                        	  return;
                        	}
                        
                        	//connector info
                        	var connectorType = this.get('type');
                        	var connector = this.getEntityId(this);
                        	if (!connector) {
                        	  if (typeof(callback) === 'function') {
                        		var error = 'Error in connect - no uuid specified.';
                        		if (self._client.logging) {
                        		  console.log(error);
                        		}
                        		callback(true, error);
                        	  }
                        	  return;
                        	}
                        
                        	var endpoint = connectorType + '/' + connector + '/' + connection + '/' + connecteeType + '/' + connectee;
                        	var options = {
                        	  method:'DELETE',
                        	  endpoint:endpoint
                        	};
                        	this._client.request(options, function (err, data) {
                        	  if (err && self._client.logging) {
                        		console.log('entity could not be disconnected');
                        	  }
                        	  if (typeof(callback) === 'function') {
                        		callback(err, data);
                        	  }
                        	});
                          }