baas.io Javascript SDK v0.9.0 src/core/core.js

IO

method
Baas.IO()

    Description

    The class models Baas io.

    @constructor
    @param {string} options - configuration object

    Source

    Baas.IO = function(options) {
    		//usergrid enpoint
    		this.URI = options.URI || '@@URI';
    
    		//Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
    		this.orgName = options.orgName;
    		this.appName = options.appName;
    
    		//other options
    		this.buildCurl = options.buildCurl || false;
    		this.logging = options.logging || false;
    
    		//timeout and callbacks
    		this._callTimeout =  options.callTimeout || 30000; //default to 30 seconds
    		this._callTimeoutCallback =  options.callTimeoutCallback || null;
    		this.logoutCallback =  options.logoutCallback || null;
    	};

    request

    method
    Baas.IO.prototype.request()

      Description

      Main function for making requests to the API. Can be called directly.

      options object:
      method - http method (GET, POST, PUT, or DELETE), defaults to GET
      qs - object containing querystring values to be appended to the uri
      body - object containing entity body for POST and PUT requests
      endpoint - API endpoint, for example 'users/fred'
      mQuery - boolean, set to true if running management query, defaults to false

      @method request
      @public
      @params {object} options
      @param {function} callback
      @return {callback} callback(err, data)

      Source

      Baas.IO.prototype.request = function (options, callback) {
      		var self = this;
      		var method = options.method || 'GET';
      		var endpoint = options.endpoint;
      		var body = options.body || {};
      		var qs = options.qs || {};
      		var mQuery = options.mQuery || false; //is this a query to the management endpoint?
      		if (mQuery) {
      			var uri = this.URI + '/' + endpoint;
      		} else {
      			var uri = this.URI + '/' + this.orgName + '/' + this.appName + '/' + endpoint;
      		}
      
      		if (self.getToken()) {
      			qs['access_token'] = self.getToken();

        Description

        //could also use headers for the token
        xhr.setRequestHeader("Authorization", "Bearer " + self.getToken());
        xhr.withCredentials = true;

        Source

        }
        
        		//append params to the path
        		var encoded_params = Baas.Utils.encodeParams(qs);
        		if (encoded_params) {
        			uri += "?" + encoded_params;
        		}
        
        		//stringify the body object
        		body = (body instanceof FormData) ? body : JSON.stringify(body);
        
        		//so far so good, so run the query
        		var xhr = new XMLHttpRequest();
        		xhr.open(method, uri, true);
        
        		// Handle response.
        		xhr.onerror = function() {
        			self._end = new Date().getTime();
        			if (self.logging) {
        				console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
        			}
        			if (self.logging) {
        				console.log('Error: API call failed at the network level.')
        			}
        			//network error
        			clearTimeout(timeout);
        			var err = true;
        			if (typeof(callback) === 'function') {
        				callback(err, data);
        			}
        		};
        
        		xhr.onload = function(response) {
        			//call timing, get time, then log the call
        			self._end = new Date().getTime();
        			if (self.logging) {
        				console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
        			}
        			//call completed
        			clearTimeout(timeout);
        
        			//download file
        			if(endpoint.indexOf('files/') >= 0 && endpoint.indexOf('/data') >= 0) {callback(false);return;}
        
        			//decode the response
        			response = JSON.parse(xhr.responseText);
        
        			if (xhr.status != 200)   {
        				//there was an api error
        				var error = response.error;
        				var error_description = response.error_description;
        				if (self.logging) {
        					console.log('Error ('+ xhr.status +')(' + error + '): ' + error_description )
        				}
        				if ( (error == "auth_expired_session_token") ||
        						(error == "auth_missing_credentials")   ||
        						(error == "auth_unverified_oath")       ||
        						(error == "expired_token")              ||
        						(error == "unauthorized")               ||
        						(error == "auth_invalid")) {
        					//these errors mean the user is not authorized for whatever reason. If a logout function is defined, call it
        					//if the user has specified a logout callback:
        					if (typeof(self.logoutCallback) === 'function') {
        						return self.logoutCallback(true, response);
        					}
        				}
        				if (typeof(callback) === 'function') {
        					callback(true, response);
        				}
        			} else {
        				if (typeof(callback) === 'function') {
        					callback(false, response);
        				}
        			}
        		};
        
        		var timeout = setTimeout(
        			function() {
        				xhr.abort();
        				if (self._callTimeoutCallback === 'function') {
        					self._callTimeoutCallback('API CALL TIMEOUT');
        				} else {
        					self.callback('API CALL TIMEOUT');
        				}
        			},
        			self._callTimeout); //set for 30 seconds
        
        		if (this.logging) {
        			console.log('calling: ' + method + ' ' + uri);
        		}
        		if (this.buildCurl) {
        			var curlOptions = {
        				uri:uri,
        				body:body,
        				method:method
        			}
        			this.buildCurlCall(curlOptions);
        		}
        		this._start = new Date().getTime();
        		xhr.send(body);
        	}

          Description

          function for building asset urls

          @method buildAssetURL
          @public
          @params {string} uuid
          @return {string} assetURL

            Description

            baas.io is not being supported 'buildAssetURL' function.

              Description

              Baas.IO.prototype.buildAssetURL = function(uuid) {
              var self = this;
              var qs = {};
              var assetURL = this.URI + '/' + this.orgName + '/' + this.appName + '/assets/' + uuid + '/data';

                   if (self.getToken()) {
                       qs['access_token'] = self.getToken();
                   }
              
                   //append params to the path
                   var encoded_params = encodeParams(qs);
                   if (encoded_params) {
                       assetURL += "?" + encoded_params;
                   }
              
                   return assetURL;
               }
              

              createGroup

              method
              Baas.IO.prototype.createGroup()

                Description

                Main function for creating new groups. Call this directly.

                @method createGroup
                @public
                @params {string} path
                @param {function} callback
                @return {callback} callback(err, data)

                Source

                Baas.IO.prototype.createGroup = function(options, callback) {
                		var getOnExist = options.getOnExist || false;
                
                		var options = {
                			path: options.path,
                			client: this,
                			data:options
                		}
                
                		var group = new Baas.Group(options);
                		group.fetch(function(err, data){
                			var okToSave = (err && 'Service resource not found' === data.error_description || 'no_name_specified' === data.error || 'null_pointer' === data.error_description) || (!err && getOnExist);
                			if (okToSave) {
                				group.save(function(err){
                					if (typeof(callback) === 'function') {
                						callback(err, group);
                					}
                				});
                			} else {
                				if(typeof(callback) === 'function') {
                					callback(err, group);
                				}
                			}
                		});
                	}

                createEntity

                method
                Baas.IO.prototype.createEntity()

                  Description

                  Main function for creating new entities - should be called directly.

                  options object: options {data:{'type':'collection_type', 'key':'value'}, uuid:uuid}}

                  @method createEntity
                  @public
                  @params {object} options
                  @param {function} callback
                  @return {callback} callback(err, data)

                  Source

                  Baas.IO.prototype.createEntity = function (options, callback) {
                  		// todo: replace the check for new / save on not found code with simple save
                  		// when users PUT on no user fix is in place.

                  getOnExist

                  declaration
                  getOnExist

                    Description

                    var options = {
                    client:this,
                    data:options
                    }
                    var entity = new Baas.Entity(options);
                    entity.save(function(err, data) {
                    if (typeof(callback) === 'function') {
                    callback(err, entity);
                    }
                    });

                    Source

                    var getOnExist = options.getOnExist || false; //if true, will return entity if one already exists
                    		var options = {
                    			client:this,
                    			data:options
                    		}
                    		var entity = new Baas.Entity(options);
                    		entity.fetch(function(err, data) {
                    			//if the fetch doesn't find what we are looking for, or there is no error, do a save
                    			var okToSave = (err && 'Service resource not found' === data.error_description || 'no_name_specified' === data.error || 'null_pointer' === data.error_description) || (!err && getOnExist);
                    			if(okToSave) {
                    				entity.set(options.data); //add the data again just in case
                    				entity.save(function(err) {
                    					if (typeof(callback) === 'function') {
                    						callback(err, entity);
                    					}
                    				});
                    			} else {
                    				if (typeof(callback) === 'function') {
                    					callback(err, entity);
                    				}
                    			}
                    		});
                    
                    	}

                    restoreEntity

                    method
                    Baas.IO.prototype.restoreEntity()

                      Description

                      Main function for restoring an entity from serialized data.

                      serializedObject should have come from entityObject.serialize();

                      @method restoreEntity
                      @public
                      @param {string} serializedObject
                      @return {object} Entity Object

                      Source

                      Baas.IO.prototype.restoreEntity = function (serializedObject) {
                      		var data = JSON.parse(serializedObject);
                      		var options = {
                      			client:this,
                      			data:data
                      		}
                      		var entity = new Baas.Entity(options);
                      		return entity;
                      	}

                      getEntity

                      method
                      Baas.IO.prototype.getEntity()

                        Description

                        Main function for getting existing entities - should be called directly.

                        You must supply a uuid or (username or name). Username only applies to users.
                        Name applies to all custom entities

                        options object: options {data:{'type':'collection_type', 'name':'value', 'username':'value'}, uuid:uuid}}

                        @method createEntity
                        @public
                        @params {object} options
                        @param {function} callback
                        @return {callback} callback(err, data)

                        Source

                        Baas.IO.prototype.getEntity = function (options, callback) {
                        		var options = {
                        			client:this,
                        			data:options
                        		}
                        		var entity = new Baas.Entity(options);
                        		entity.fetch(function(err) {
                        			if (typeof(callback) === 'function') {
                        				callback(err, entity);
                        			}
                        		});
                        	}

                        createCollection

                        method
                        Baas.IO.prototype.createCollection()

                          Description

                          Main function for creating new collections - should be called directly.

                          options object: options {client:client, type: type, qs:qs}

                          @method createCollection
                          @public
                          @params {object} options
                          @param {function} callback
                          @return {callback} callback(err, data)

                          Source

                          Baas.IO.prototype.createCollection = function (options, callback) {
                          		options.client = this;
                          		var collection = new Baas.Collection(options, function(err) {
                          			if (typeof(callback) === 'function') {
                          				callback(err, collection);
                          			}
                          		});
                          	}

                          restoreCollection

                          method
                          Baas.IO.prototype.restoreCollection()

                            Description

                            Main function for restoring a collection from serialized data.

                            serializedObject should have come from collectionObject.serialize();

                            @method restoreCollection
                            @public
                            @param {string} serializedObject
                            @return {object} Collection Object

                            Source

                            Baas.IO.prototype.restoreCollection = function (serializedObject) {
                            		var data = JSON.parse(serializedObject);
                            		data.client = this;
                            		var collection = new Baas.Collection(data);
                            		return collection;
                            	}

                            getFeedForUser

                            method
                            Baas.IO.prototype.getFeedForUser()

                              Description

                              Main function for retrieving a user's activity feed.

                              @method getFeedForUser
                              @public
                              @params {string} username or uuid or email
                              @param {function} callback
                              @return {callback} callback(err, data, activities)

                              Source

                              Baas.IO.prototype.getFeedForUser = function(username, callback) {
                              		var options = {
                              			method: "GET",
                              			endpoint: "users/"+username+"/feed"
                              		}
                              
                              		this.request(options, function(err, data){
                              			if(typeof(callback) === "function") {
                              				if(err) {
                              					callback(err);
                              				} else {
                              					callback(err, data, data.entities);
                              				}
                              			}
                              		});
                              	}

                              createUserActivity

                              method
                              Baas.IO.prototype.createUserActivity()

                                Description

                                Function for creating new activities for the current user - should be called directly.

                                //user can be any of the following: "me", a uuid, a username
                                Note: the "me" alias will reference the currently logged in user (e.g. 'users/me/activties')

                                //build a json object that looks like this:
                                var options =
                                {
                                "actor" : {
                                "displayName" :"myusername",
                                "uuid" : "myuserid",
                                "username" : "myusername",
                                "email" : "myemail",
                                "picture": "http://path/to/picture",
                                "image" : {
                                "duration" : 0,
                                "height" : 80,
                                "url" : "http://www.gravatar.com/avatar/",
                                "width" : 80
                                },
                                },
                                "verb" : "post",
                                "content" : "My cool message",
                                "lat" : 48.856614,
                                "lon" : 2.352222
                                }

                                @method createEntity
                                @public
                                @params {string} user // "me", a uuid, or a username
                                @params {object} options
                                @param {function} callback
                                @return {callback} callback(err, data)

                                Source

                                Baas.IO.prototype.createUserActivity = function (user, options, callback) {
                                		options.type = 'users/'+user+'/activities';
                                		var options = {
                                			client:this,
                                			data:options
                                		}
                                		var entity = new Baas.Entity(options);
                                		entity.save(function(err) {
                                			if (typeof(callback) === 'function') {
                                				callback(err, entity);
                                			}
                                		});
                                	}

                                createUserActivityWithEntity

                                method
                                Baas.IO.prototype.createUserActivityWithEntity()

                                  Description

                                  Function for creating user activities with an associated user entity.

                                  user object:
                                  The user object passed into this function is an instance of Baas.Entity.

                                  @method createUserActivityWithEntity
                                  @public
                                  @params {object} user
                                  @params {string} content
                                  @param {function} callback
                                  @return {callback} callback(err, data)

                                  Source

                                  Baas.IO.prototype.createUserActivityWithEntity = function(user, content, callback) {
                                  		var username = user.get("username");
                                  		var options = {
                                  			actor: {
                                  				"displayName":username,
                                  				"uuid":user.get("uuid"),
                                  				"username":username,
                                  				"email":user.get("email"),
                                  				"picture":user.get("picture"),
                                  				"image": {
                                  					"duration":0,
                                  					"height":80,
                                  					"url":user.get("picture"),
                                  					"width":80
                                  				 },
                                  			},
                                  			"verb":"post",
                                  			"content":content };
                                  
                                  			this.createUserActivity(username, options, callback);
                                  	}

                                  calcTimeDiff

                                  method
                                  Baas.IO.prototype.calcTimeDiff()

                                    Description

                                    A private method to get call timing of last call

                                    Source

                                    Baas.IO.prototype.calcTimeDiff = function () {
                                    	 var seconds = 0;
                                    	 var time = this._end - this._start;
                                    	 try {
                                    			seconds = ((time/10) / 60).toFixed(2);
                                    	 } catch(e) { return 0; }
                                    	 return seconds;
                                    	}

                                    setToken

                                    method
                                    Baas.IO.prototype.setToken()

                                      Description

                                      A public method to store the OAuth token for later use - uses localstorage if available

                                      @method setToken
                                      @public
                                      @params {string} token
                                      @return none

                                      Source

                                      Baas.IO.prototype.setToken = function (token) {
                                      		var tokenKey = 'token' + this.appName + this.orgName;
                                      		this.token = token;
                                      		if(typeof(Storage)!=="undefined"){
                                      			if (token) {
                                      				localStorage.setItem(tokenKey, token);
                                      			} else {
                                      				localStorage.removeItem(tokenKey);
                                      			}
                                      		}
                                      	}

                                      getToken

                                      method
                                      Baas.IO.prototype.getToken()

                                        Description

                                        A public method to get the OAuth token

                                        @method getToken
                                        @public
                                        @return {string} token

                                        Source

                                        Baas.IO.prototype.getToken = function () {
                                        		var tokenKey = 'token' + this.appName + this.orgName;
                                        		if (this.token) {
                                        			return this.token;
                                        		} else if(typeof(Storage)!=="undefined") {
                                        			return localStorage.getItem(tokenKey);
                                        		}
                                        		return null;
                                        	}

                                        signup

                                        method
                                        Baas.IO.prototype.signup()
                                        • @method: signup
                                        • @public:
                                        • @params: {string} username
                                        • @params: {string} password
                                        • @params: {string} email
                                        • @params: {string} name
                                        • @param: {function}callback
                                        • @return: {callback}callback(err, data)

                                        Description

                                        A public facing helper method for signing up users

                                        Source

                                        Baas.IO.prototype.signup = function(username, password, email, name, callback) {
                                        		var options = {
                                        			type:"users",
                                        			username:username,
                                        			password:password,
                                        			email:email,
                                        			name:name
                                        		};
                                        
                                        		this.createEntity(options, callback);
                                        	}

                                        login

                                        method
                                        Baas.IO.prototype.login()

                                          Description

                                          A public method to log in an app user - stores the token for later use

                                          @method login
                                          @public
                                          @params {string} username
                                          @params {string} password
                                          @param {function} callback
                                          @return {callback} callback(err, data)

                                          Source

                                          Baas.IO.prototype.login = function (username, password, callback) {
                                          		var self = this;
                                          		var options = {
                                          			method:'POST',
                                          			endpoint:'token',
                                          			body:{
                                          				username: username,
                                          				password: password,
                                          				grant_type: 'password'
                                          			}
                                          		};
                                          		this.request(options, function(err, data) {
                                          			var user = {};
                                          			if (err && self.logging) {
                                          				console.log('error trying to log user in');
                                          			} else {
                                          				var options = {
                                          					client:self,
                                          					data:data.user
                                          				}
                                          				user = new Baas.Entity(options);
                                          				self.setToken(data.access_token);
                                          			}
                                          			if (typeof(callback) === 'function') {
                                          				callback(err, data, user);
                                          			}
                                          		});
                                          	}

                                          loginFacebook

                                          method
                                          Baas.IO.prototype.loginFacebook()

                                            Description

                                            A public method to log in an app user with facebook - stores the token for later use

                                            @method loginFacebook
                                            @public
                                            @params {string} username
                                            @params {string} password
                                            @param {function} callback
                                            @return {callback} callback(err, data)

                                            Source

                                            Baas.IO.prototype.loginFacebook = function (facebookToken, callback) {
                                            		var self = this;
                                            		var options = {
                                            			method:'GET',
                                            			endpoint:'auth/facebook',
                                            			qs:{
                                            				fb_access_token: facebookToken
                                            			}
                                            		};
                                            		this.request(options, function(err, data) {
                                            			var user = {};
                                            			if (err && self.logging) {
                                            				console.log('error trying to log user in');
                                            			} else {
                                            				var options = {
                                            					client: self,
                                            					data: data.user
                                            				}
                                            				user = new Baas.Entity(options);
                                            				self.setToken(data.access_token);
                                            			}
                                            			if (typeof(callback) === 'function') {
                                            				callback(err, data, user);
                                            			}
                                            		});
                                            	}

                                            getLoggedInUser

                                            method
                                            Baas.IO.prototype.getLoggedInUser()

                                              Description

                                              A public method to get the currently logged in user entity

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

                                              Source

                                              Baas.IO.prototype.getLoggedInUser = function (callback) {
                                              		if (!this.getToken()) {
                                              			callback(true, null, null);
                                              		} else {
                                              			var self = this;
                                              			var options = {
                                              				method:'GET',
                                              				endpoint:'users/me',
                                              			};
                                              			this.request(options, function(err, data) {
                                              				if (err) {
                                              					if (self.logging) {
                                              						console.log('error trying to log user in');
                                              					}
                                              					if (typeof(callback) === 'function') {
                                              						callback(err, data, null);
                                              					}
                                              				} else {
                                              					var options = {
                                              						client:self,
                                              						data:data.entities[0]
                                              					}
                                              					var user = new Baas.Entity(options);
                                              					if (typeof(callback) === 'function') {
                                              						callback(err, data, user);
                                              					}
                                              				}
                                              			});
                                              		}
                                              	}

                                              isLoggedIn

                                              method
                                              Baas.IO.prototype.isLoggedIn()

                                                Description

                                                A public method to test if a user is logged in - does not guarantee that the token is still valid,
                                                but rather that one exists

                                                @method isLoggedIn
                                                @public
                                                @return {boolean} Returns true the user is logged in (has token and uuid), false if not

                                                Source

                                                Baas.IO.prototype.isLoggedIn = function () {
                                                		if (this.getToken() && this.getToken() != 'null') {
                                                			return true;
                                                		}
                                                		return false;
                                                	}

                                                logout

                                                method
                                                Baas.IO.prototype.logout()

                                                  Description

                                                  A public method to log out an app user - clears all user fields from client

                                                  @method logout
                                                  @public
                                                  @return none

                                                  Source

                                                  Baas.IO.prototype.logout = function () {
                                                  		this.setToken(null);
                                                  	}

                                                  buildCurlCall

                                                  method
                                                  Baas.IO.prototype.buildCurlCall()

                                                    Description

                                                    A private method to build the curl call to display on the command line

                                                    @method buildCurlCall
                                                    @private
                                                    @param {object} options
                                                    @return {string} curl

                                                    Source

                                                    Baas.IO.prototype.buildCurlCall = function (options) {
                                                    		var curl = 'curl';
                                                    		var method = (options.method || 'GET').toUpperCase();
                                                    		var body = options.body || {};
                                                    		var uri = options.uri;
                                                    
                                                    		//curl - add the method to the command (no need to add anything for GET)
                                                    		if (method === 'POST') {curl += ' -X POST'; }
                                                    		else if (method === 'PUT') { curl += ' -X PUT'; }
                                                    		else if (method === 'DELETE') { curl += ' -X DELETE'; }
                                                    		else { curl += ' -X GET'; }
                                                    
                                                    		//curl - append the path
                                                    		curl += ' ' + uri;
                                                    
                                                    		//curl - add the body
                                                    		if (body !== '"{}"' && method !== 'GET' && method !== 'DELETE') {
                                                    			//curl - add in the json obj
                                                    			curl += " -d '" + body + "'";
                                                    		}
                                                    
                                                    		//log the curl command to the console
                                                    		console.log(curl);
                                                    
                                                    		return curl;
                                                    	}