You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by sf...@apache.org on 2014/09/24 21:42:11 UTC
[1/2] fix create collections
Repository: incubator-usergrid
Updated Branches:
refs/heads/two-dot-o-candidate e0f7b490a -> d972699b5
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d972699b/portal/js/libs/usergrid.sdk.js
----------------------------------------------------------------------
diff --git a/portal/js/libs/usergrid.sdk.js b/portal/js/libs/usergrid.sdk.js
index 824f293..795e3e2 100755
--- a/portal/js/libs/usergrid.sdk.js
+++ b/portal/js/libs/usergrid.sdk.js
@@ -1,278 +1,293 @@
/*
-* This module is a collection of classes designed to make working with
-* the Appigee App Services API as easy as possible.
-* Learn more at http://apigee.com/docs/usergrid
-*
-* Copyright 2012 Apigee Corporation
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-* @author rod simpson (rod@apigee.com)
-*/
-(function(window, localStorage){
+ * This module is a collection of classes designed to make working with
+ * the Appigee App Services API as easy as possible.
+ * Learn more at http://apigee.com/docs/usergrid
+ *
+ * Copyright 2012 Apigee Corporation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @author rod simpson (rod@apigee.com)
+ */
+(function(window, localStorage) {
-//Hack around IE console.log
-window.console = window.console || {};
-window.console.log = window.console.log || function() {};
+ //Hack around IE console.log
+ window.console = window.console || {};
+ window.console.log = window.console.log || function() {};
-//Usergrid namespace encapsulates this SDK
-window.Usergrid = window.Usergrid || {};
-Usergrid = Usergrid || {};
-Usergrid.SDK_VERSION = '0.10.07';
-Usergrid.browser = Usergrid.browser || {};
+ //Usergrid namespace encapsulates this SDK
+ window.Usergrid = window.Usergrid || {};
+ Usergrid = Usergrid || {};
+ Usergrid.SDK_VERSION = '0.10.07';
+ Usergrid.browser = Usergrid.browser || {};
-Usergrid.Client = function(options,url) {
- //usergrid enpoint
- this.URI = url || 'https://api.usergrid.com';
+ Usergrid.Client = function(options, url) {
+ //usergrid enpoint
+ this.URI = url || 'https://api.usergrid.com';
- //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
- if (options.orgName) {
- this.set('orgName', options.orgName);
- }
- if (options.appName) {
- this.set('appName', options.appName);
- }
+ //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
+ if (options.orgName) {
+ this.set('orgName', options.orgName);
+ }
+ if (options.appName) {
+ this.set('appName', options.appName);
+ }
- if(options.keys){
- this._keys = options.keys;
- }
+ if (options.keys) {
+ this._keys = options.keys;
+ }
- //other options
- this.buildCurl = options.buildCurl || false;
- this.logging = options.logging || false;
+ //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;
-};
+ //timeout and callbacks
+ this._callTimeout = options.callTimeout || 30000; //default to 30 seconds
+ this._callTimeoutCallback = options.callTimeoutCallback || null;
+ this.logoutCallback = options.logoutCallback || null;
+ };
-/*
-* 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)
-*/
-Usergrid.Client.prototype.request = function (options, callback) {
- callback = callback || function(){console.error('no callback handed to client.request().')};
- 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?
- var orgName = this.get("orgName");
- var appName = this.get("appName");
- if (!mQuery && !orgName && !appName) {
- if (typeof this.logoutCallback === "function") {
- return this.logoutCallback(true, "no_org_or_app_name_specified");
- }
- }
- var uri;
- if (mQuery) {
- uri = this.URI + "/" + endpoint;
- } else {
- uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint;
- }
- if (self.getToken()) {
- qs.access_token = self.getToken();
- }
- var developerkey=self.get("developerkey");
- if (developerkey) {
- qs.key = developerkey;
- }
-
- var isIE9 = Usergrid.browser.isIE9 = $.browser.msie && $.browser.version <= 9;
-
- (isIE9) && (method === 'PUT' || method === 'DELETE') && (function(){ qs['method_override'] = method;})();
-
- //append params to the path
- var encoded_params = encodeParams(qs);
- if (encoded_params) {
- uri += "?" + encoded_params;
- }
- //stringify the body object
- body = options.formData ? null : JSON.stringify(body);
- //so far so good, so run the query
- //*** ie9 hack
- var xhr;
- //check to see if ie9 - if so, convert delete and put calls to a POST
- if (isIE9) { //XDomainRequest
- xhr = new XDomainRequest();
- (method === 'PUT' || method === 'DELETE') && (function() { method = 'POST';})();
- xhr.open(method, uri);
- }else{
- xhr = new XMLHttpRequest();
- xhr.open(method, uri, true);
- //add content type = json if there is a json payload
- if (!options.formData) {
- xhr.setRequestHeader("Content-Type", "application/json");
- xhr.setRequestHeader("Accept", "application/json");
- }
- }
- xhr.isIE9 = isIE9;
- // Handle response.
- xhr.onerror = function(response) {
- 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, response);
+ /*
+ * 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)
+ */
+ Usergrid.Client.prototype.request = function(options, callback) {
+ callback = callback || function() {
+ console.error('no callback handed to client.request().')
+ };
+ 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?
+ var orgName = this.get("orgName");
+ var appName = this.get("appName");
+ if (!mQuery && !orgName && !appName) {
+ if (typeof this.logoutCallback === "function") {
+ return this.logoutCallback(true, "no_org_or_app_name_specified");
+ }
}
- };
- 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);
- //decode the response
- try {
- response = JSON.parse(xhr.responseText);
- } catch (e) {
- response = {
- error: "unhandled_error",
- error_description: xhr.responseText
- };
- xhr.status = xhr.status === 200 ? 400 : xhr.status;
- console.error(e);
+ var uri;
+ if (mQuery) {
+ uri = this.URI + "/" + endpoint;
+ } else {
+ uri = this.URI + "/" + orgName + "/" + appName + "/" + endpoint;
+ }
+ if (self.getToken()) {
+ qs.access_token = self.getToken();
+ }
+ var developerkey = self.get("developerkey");
+ if (developerkey) {
+ qs.key = developerkey;
+ }
+
+ var isIE9 = Usergrid.browser.isIE9 = $.browser.msie && $.browser.version <=
+ 9;
+
+ (isIE9) && (method === 'PUT' || method === 'DELETE') && (function() {
+ qs['method_override'] = method;
+ })();
+
+ //append params to the path
+ var encoded_params = encodeParams(qs);
+ if (encoded_params) {
+ uri += "?" + encoded_params;
+ }
+ //stringify the body object
+ body = options.formData ? null : JSON.stringify(body);
+ //so far so good, so run the query
+ //*** ie9 hack
+ var xhr;
+ //check to see if ie9 - if so, convert delete and put calls to a POST
+ if (isIE9) { //XDomainRequest
+ xhr = new XDomainRequest();
+ (method === 'PUT' || method === 'DELETE') && (function() {
+ method = 'POST';
+ })();
+ xhr.open(method, uri);
+ } else {
+ xhr = new XMLHttpRequest();
+ xhr.open(method, uri, true);
+ //add content type = json if there is a json payload
+ if (!options.formData) {
+ xhr.setRequestHeader("Content-Type", "application/json");
+ xhr.setRequestHeader("Accept", "application/json");
+ }
}
- if (!xhr.isIE9 && xhr.status != 200) {
- //there was an api error
- var error = response.error;
- var error_description = response.error_description;
+ xhr.isIE9 = isIE9;
+ // Handle response.
+ xhr.onerror = function(response) {
+ self._end = new Date().getTime();
if (self.logging) {
- console.log("Error (" + xhr.status + ")(" + error + "): " + error_description);
+ console.log("success (time: " + self.calcTimeDiff() + "): " + method +
+ " " + uri);
}
- 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 (self.logging) {
+ console.log("Error: API call failed at the network level.");
}
+ //network error
+ clearTimeout(timeout);
+ var err = true;
if (typeof callback === "function") {
- callback(true, response);
+ callback(err, response);
}
- } else {
- if (typeof callback === "function") {
- callback(false, response);
+ };
+ 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);
+ //decode the response
+ try {
+ response = JSON.parse(xhr.responseText);
+ } catch (e) {
+ response = {
+ error: "unhandled_error",
+ error_description: xhr.responseText
+ };
+ xhr.status = xhr.status === 200 ? 400 : xhr.status;
+ console.error(e);
+ }
+ if (!xhr.isIE9 && 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 {
+ 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(options.formData || body);
};
- var timeout = setTimeout(function() {
- xhr.abort();
- if (self._callTimeoutCallback === "function") {
- self._callTimeoutCallback("API CALL TIMEOUT");
- } else {
- 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(options.formData || body);
-};
-Usergrid.Client.prototype.keys = function(o) {
- var a = [];
- for (var propertyName in o) {
- a.push(propertyName);
+ Usergrid.Client.prototype.keys = function(o) {
+ var a = [];
+ for (var propertyName in o) {
+ a.push(propertyName);
+ }
+ return a;
}
- return a;
-}
-
-/*
- * Main function for creating new groups. Call this directly.
- *
- * @method createGroup
- * @public
- * @params {string} path
- * @param {function} callback
- * @return {callback} callback(err, data)
- */
-Usergrid.Client.prototype.createGroup = function(options, callback) {
- var getOnExist = options.getOnExist || false;
- var options = {
- path: options.path,
- client: this,
- data:options
- }
+ /*
+ * Main function for creating new groups. Call this directly.
+ *
+ * @method createGroup
+ * @public
+ * @params {string} path
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createGroup = function(options, callback) {
+ var getOnExist = options.getOnExist || false;
- var group = new Usergrid.Group(options);
- group.fetch(function(err, data){
- var okToSave = (err && ('service_resource_not_found' === data.error || 'no_name_specified' === data.error || 'null_pointer' === data.error || Usergrid.browser.isIE9)) || (!err && getOnExist);
- if (okToSave) {
- group.save(function(err, data){
+ var options = {
+ path: options.path,
+ client: this,
+ data: options
+ }
+
+ var group = new Usergrid.Group(options);
+ group.fetch(function(err, data) {
+ var okToSave = (err && ('service_resource_not_found' === data.error ||
+ 'no_name_specified' === data.error || 'null_pointer' === data.error ||
+ Usergrid.browser.isIE9)) || (!err && getOnExist);
+ if (okToSave) {
+ group.save(function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, group);
+ }
+ });
+ } else {
if (typeof(callback) === 'function') {
callback(err, group);
}
- });
- } else {
- if(typeof(callback) === 'function') {
- callback(err, group);
}
- }
- });
-}
+ });
+ }
-/*
-* 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)
-*/
-Usergrid.Client.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.
/*
+ * 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)
+ */
+ Usergrid.Client.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.
+ /*
var options = {
client:this,
data:options
@@ -284,150 +299,152 @@ Usergrid.Client.prototype.createEntity = function (options, callback) {
}
});
*/
- var getOnExist = options.getOnExist || false; //if true, will return entity if one already exists
- var options = {
- client:this,
- data:options
- }
- var entity = new Usergrid.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
- if (Usergrid.browser.isIE9 || 'service_resource_not_found' === data.error || 'no_name_specified' === data.error || 'null_pointer' === data.error) {
-
- entity.set(options.data); //add the data again just in case
- entity.save(function(err, data) {
- if (typeof(callback) === 'function') {
- callback(err, entity, data);
- }
- });
+ var getOnExist = options.getOnExist || false; //if true, will return entity if one already exists
+ var options = {
+ client: this,
+ data: options
+ }
+ var entity = new Usergrid.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
+ if (Usergrid.browser.isIE9 || 'service_resource_not_found' === data.error ||
+ 'no_name_specified' === data.error || 'null_pointer' === data.error
+ ) {
+
+ entity.set(options.data); //add the data again just in case
+ entity.save(function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, entity, data);
+ }
+ });
- } else {
- if (getOnExist) {
- // entity exists and they want it returned
- if (typeof(callback) === 'function') {
- callback(err, entity, data);
- }
} else {
- //entity exists but they want an error to that effect
- err = true;
- callback(err, 'duplicate entity already exists');
+ if (getOnExist) {
+ // entity exists and they want it returned
+ if (typeof(callback) === 'function') {
+ callback(err, entity, data);
+ }
+ } else {
+ //entity exists but they want an error to that effect
+ err = true;
+ callback(err, 'duplicate entity already exists');
+ }
}
- }
- });
-
-}
+ });
-/*
- * 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)
- */
-Usergrid.Client.prototype.getEntity = function (options, callback) {
- var options = {
- client:this,
- data:options
}
- var entity = new Usergrid.Entity(options);
- entity.fetch(function(err, data) {
- if (typeof(callback) === 'function') {
- callback(err, entity, data);
+
+ /*
+ * 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)
+ */
+ Usergrid.Client.prototype.getEntity = function(options, callback) {
+ var options = {
+ client: this,
+ data: options
}
- });
-}
-/*
- * 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
- */
-Usergrid.Client.prototype.restoreEntity = function (serializedObject) {
- var data = JSON.parse(serializedObject);
- var options = {
- client:this,
- data:data
+ var entity = new Usergrid.Entity(options);
+ entity.fetch(function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, entity, data);
+ }
+ });
}
- var entity = new Usergrid.Entity(options);
- return entity;
-}
-
-/*
-* 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)
-*/
-Usergrid.Client.prototype.createCollection = function (options, callback) {
- options.client = this;
- var collection = new Usergrid.Collection(options, function(err, data) {
- if (typeof(callback) === 'function') {
- callback(err, collection, data);
+ /*
+ * 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
+ */
+ Usergrid.Client.prototype.restoreEntity = function(serializedObject) {
+ var data = JSON.parse(serializedObject);
+ var options = {
+ client: this,
+ data: data
}
- });
-}
+ var entity = new Usergrid.Entity(options);
+ return entity;
+ }
-/*
- * 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
- */
-Usergrid.Client.prototype.restoreCollection = function (serializedObject) {
- var data = JSON.parse(serializedObject);
- data.client = this;
- var collection = new Usergrid.Collection(data);
- return collection;
-}
+ /*
+ * 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)
+ */
+ Usergrid.Client.prototype.createCollection = function(options, callback) {
+ options.client = this;
+ var collection = new Usergrid.Collection(options, function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, collection, data);
+ }
+ });
+ }
-/*
- * Main function for retrieving a user's activity feed.
- *
- * @method getFeedForUser
- * @public
- * @params {string} username
- * @param {function} callback
- * @return {callback} callback(err, data, activities)
- */
-Usergrid.Client.prototype.getFeedForUser = function(username, callback) {
- var options = {
- method: "GET",
- endpoint: "users/"+username+"/feed"
+ /*
+ * 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
+ */
+ Usergrid.Client.prototype.restoreCollection = function(serializedObject) {
+ var data = JSON.parse(serializedObject);
+ data.client = this;
+ var collection = new Usergrid.Collection(data);
+ return collection;
}
- this.request(options, function(err, data){
- if(typeof(callback) === "function") {
- if(err) {
- callback(err);
- } else {
- callback(err, data, data.entities);
- }
+ /*
+ * Main function for retrieving a user's activity feed.
+ *
+ * @method getFeedForUser
+ * @public
+ * @params {string} username
+ * @param {function} callback
+ * @return {callback} callback(err, data, activities)
+ */
+ Usergrid.Client.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);
+ }
+ }
+ });
+ }
+
+ /*
* 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
@@ -463,388 +480,408 @@ Usergrid.Client.prototype.getFeedForUser = function(username, callback) {
* @param {function} callback
* @return {callback} callback(err, data)
*/
-Usergrid.Client.prototype.createUserActivity = function (user, options, callback) {
- options.type = 'users/'+user+'/activities';
- var options = {
- client:this,
- data:options
- }
- var entity = new Usergrid.Entity(options);
- entity.save(function(err, data) {
- if (typeof(callback) === 'function') {
- callback(err, entity);
+ Usergrid.Client.prototype.createUserActivity = function(user, options,
+ callback) {
+ options.type = 'users/' + user + '/activities';
+ var options = {
+ client: this,
+ data: options
}
- });
-}
+ var entity = new Usergrid.Entity(options);
+ entity.save(function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, entity);
+ }
+ });
+ }
-/*
- * Function for creating user activities with an associated user entity.
- *
- * user object:
- * The user object passed into this function is an instance of Usergrid.Entity.
- *
- * @method createUserActivityWithEntity
- * @public
- * @params {object} user
- * @params {string} content
- * @param {function} callback
- * @return {callback} callback(err, data)
- */
-Usergrid.Client.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 };
+ /*
+ * Function for creating user activities with an associated user entity.
+ *
+ * user object:
+ * The user object passed into this function is an instance of Usergrid.Entity.
+ *
+ * @method createUserActivityWithEntity
+ * @public
+ * @params {object} user
+ * @params {string} content
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.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);
-}
-
-/*
-* A private method to get call timing of last call
-*/
-Usergrid.Client.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;
-}
+ }
-/*
- * A public method to store the OAuth token for later use - uses localstorage if available
- *
- * @method setToken
- * @public
- * @params {string} token
- * @return none
- */
-Usergrid.Client.prototype.setToken = function (token) {
- this.set('token', token);
-}
+ /*
+ * A private method to get call timing of last call
+ */
+ Usergrid.Client.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;
+ }
-/*
- * A public method to get the OAuth token
- *
- * @method getToken
- * @public
- * @return {string} token
- */
-Usergrid.Client.prototype.getToken = function () {
- return this.get('token');
-}
+ /*
+ * A public method to store the OAuth token for later use - uses localstorage if available
+ *
+ * @method setToken
+ * @public
+ * @params {string} token
+ * @return none
+ */
+ Usergrid.Client.prototype.setToken = function(token) {
+ this.set('token', token);
+ }
-Usergrid.Client.prototype.setObject = function(key, value) {
- if (value) {
- value = JSON.stringify(value);
+ /*
+ * A public method to get the OAuth token
+ *
+ * @method getToken
+ * @public
+ * @return {string} token
+ */
+ Usergrid.Client.prototype.getToken = function() {
+ return this.get('token');
}
- this.set(key, value);
-}
-Usergrid.Client.prototype.set = function (key, value) {
- var keyStore = 'apigee_' + key;
- this[key] = value;
- if(typeof(Storage)!=="undefined"){
+ Usergrid.Client.prototype.setObject = function(key, value) {
if (value) {
- localStorage.setItem(keyStore, value);
- } else {
- localStorage.removeItem(keyStore);
+ value = JSON.stringify(value);
}
+ this.set(key, value);
}
-}
-
-Usergrid.Client.prototype.getObject = function(key) {
- return JSON.parse(this.get(key));
-}
-Usergrid.Client.prototype.get = function (key) {
- var keyStore = 'apigee_' + key;
- if (this[key]) {
- return this[key];
- } else if(typeof(Storage)!=="undefined") {
- return localStorage.getItem(keyStore);
+ Usergrid.Client.prototype.set = function(key, value) {
+ var keyStore = 'apigee_' + key;
+ this[key] = value;
+ if (typeof(Storage) !== "undefined") {
+ if (value) {
+ localStorage.setItem(keyStore, value);
+ } else {
+ localStorage.removeItem(keyStore);
+ }
+ }
}
- return null;
-}
-/*
- * A public facing helper method for signing up users
- *
- * @method signup
- * @public
- * @params {string} username
- * @params {string} password
- * @params {string} email
- * @params {string} name
- * @param {function} callback
- * @return {callback} callback(err, data)
- */
-Usergrid.Client.prototype.signup = function(username, password, email, name, callback) {
- var self = this;
- var options = {
- type:"users",
- username:username,
- password:password,
- email:email,
- name:name
- };
+ Usergrid.Client.prototype.getObject = function(key) {
+ return JSON.parse(this.get(key));
+ }
- this.createEntity(options, callback);
-}
+ Usergrid.Client.prototype.get = function(key) {
+ var keyStore = 'apigee_' + key;
+ if (this[key]) {
+ return this[key];
+ } else if (typeof(Storage) !== "undefined") {
+ return localStorage.getItem(keyStore);
+ }
+ return null;
+ }
-/*
-*
-* 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)
-*/
-Usergrid.Client.prototype.login = function (username, password, callback) {
- var self = this;
- var options = {
- method:'POST',
- endpoint:'token',
- body:{
+ /*
+ * A public facing helper method for signing up users
+ *
+ * @method signup
+ * @public
+ * @params {string} username
+ * @params {string} password
+ * @params {string} email
+ * @params {string} name
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.signup = function(username, password, email, name,
+ callback) {
+ var self = this;
+ var options = {
+ type: "users",
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 Usergrid.Entity(options);
- self.setToken(data.access_token);
- }
- if (typeof(callback) === 'function') {
- callback(err, data, user);
- }
- });
-}
-
-
-Usergrid.Client.prototype.reAuthenticateLite = function (callback) {
- var self = this;
- var options = {
- method:'GET',
- endpoint:'management/me',
- mQuery:true
- };
- this.request(options, function(err, response) {
- if (err && self.logging) {
- console.log('error trying to re-authenticate user');
- } else {
-
- //save the re-authed token and current email/username
- self.setToken(response.access_token);
+ email: email,
+ name: name
+ };
- }
- if (typeof(callback) === 'function') {
- callback(err);
- }
- });
-}
+ this.createEntity(options, callback);
+ }
+ /*
+ *
+ * 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)
+ */
+ Usergrid.Client.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 Usergrid.Entity(options);
+ self.setToken(data.access_token);
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data, user);
+ }
+ });
+ }
-Usergrid.Client.prototype.reAuthenticate = function (email, callback) {
- var self = this;
- var options = {
- method:'GET',
- endpoint:'management/users/'+email,
- mQuery:true
- };
- this.request(options, function(err, response) {
- var organizations = {};
- var applications = {};
- var user = {};
- if (err && self.logging) {
- console.log('error trying to full authenticate user');
- } else {
- var data = response.data;
- self.setToken(data.token);
- self.set('email', data.email);
- //delete next block and corresponding function when iframes are refactored
- localStorage.setItem('accessToken', data.token);
- localStorage.setItem('userUUID', data.uuid);
- localStorage.setItem('userEmail', data.email);
- //end delete block
+ Usergrid.Client.prototype.reAuthenticateLite = function(callback) {
+ var self = this;
+ var options = {
+ method: 'GET',
+ endpoint: 'management/me',
+ mQuery: true
+ };
+ this.request(options, function(err, response) {
+ if (err && self.logging) {
+ console.log('error trying to re-authenticate user');
+ } else {
+ //save the re-authed token and current email/username
+ self.setToken(response.access_token);
- var userData = {
- "username" : data.username,
- "email" : data.email,
- "name" : data.name,
- "uuid" : data.uuid
}
- var options = {
- client:self,
- data:userData
+ if (typeof(callback) === 'function') {
+ callback(err);
}
- user = new Usergrid.Entity(options);
+ });
+ }
- organizations = data.organizations;
- var org = '';
- try {
- //if we have an org stored, then use that one. Otherwise, use the first one.
- var existingOrg = self.get('orgName');
- org = (organizations[existingOrg])?organizations[existingOrg]:organizations[Object.keys(organizations)[0]];
- self.set('orgName', org.name);
- } catch(e) {
- err = true;
- if (self.logging) { console.log('error selecting org'); }
- } //should always be an org
-
- applications = self.parseApplicationsArray(org);
- self.selectFirstApp(applications);
- self.setObject('organizations', organizations);
- self.setObject('applications', applications);
+ Usergrid.Client.prototype.reAuthenticate = function(email, callback) {
+ var self = this;
+ var options = {
+ method: 'GET',
+ endpoint: 'management/users/' + email,
+ mQuery: true
+ };
+ this.request(options, function(err, response) {
+ var organizations = {};
+ var applications = {};
+ var user = {};
+ if (err && self.logging) {
+ console.log('error trying to full authenticate user');
+ } else {
+ var data = response.data;
+ self.setToken(data.token);
+ self.set('email', data.email);
+
+ //delete next block and corresponding function when iframes are refactored
+ localStorage.setItem('accessToken', data.token);
+ localStorage.setItem('userUUID', data.uuid);
+ localStorage.setItem('userEmail', data.email);
+ //end delete block
+
+
+ var userData = {
+ "username": data.username,
+ "email": data.email,
+ "name": data.name,
+ "uuid": data.uuid
+ }
+ var options = {
+ client: self,
+ data: userData
+ }
+ user = new Usergrid.Entity(options);
+
+ organizations = data.organizations;
+ var org = '';
+ try {
+ //if we have an org stored, then use that one. Otherwise, use the first one.
+ var existingOrg = self.get('orgName');
+ org = (organizations[existingOrg]) ? organizations[existingOrg] :
+ organizations[Object.keys(organizations)[0]];
+ self.set('orgName', org.name);
+ } catch (e) {
+ err = true;
+ if (self.logging) {
+ console.log('error selecting org');
+ }
+ } //should always be an org
- }
- if (typeof(callback) === 'function') {
- callback(err, data, user, organizations, applications);
- }
- });
-}
+ applications = self.parseApplicationsArray(org);
+ self.selectFirstApp(applications);
+
+ self.setObject('organizations', organizations);
+ self.setObject('applications', applications);
-Usergrid.Client.prototype.orgLogin = function (username, password, callback) {
- var self = this;
- var options = {
- method:'POST',
- endpoint:'management/token',
- mQuery:true,
- body:{
- username: username,
- password: password,
- grant_type: 'password'
- }
- };
- this.request(options, function(err, data) {
- var user = {};
- var organizations = {};
- var applications = {};
- if (err && self.logging) {
- console.log('error trying to log user in');
- } else {
- var options = {
- client:self,
- data:data.user
}
- user = new Usergrid.Entity(options);
- self.setToken(data.access_token);
- self.set('email', data.user.email);
+ if (typeof(callback) === 'function') {
+ callback(err, data, user, organizations, applications);
+ }
+ });
+ }
+ Usergrid.Client.prototype.orgLogin = function(username, password, callback) {
+ var self = this;
+ var options = {
+ method: 'POST',
+ endpoint: 'management/token',
+ mQuery: true,
+ body: {
+ username: username,
+ password: password,
+ grant_type: 'password'
+ }
+ };
+ this.request(options, function(err, data) {
+ var user = {};
+ var organizations = {};
+ var applications = {};
+ if (err && self.logging) {
+ console.log('error trying to log user in');
+ } else {
+ var options = {
+ client: self,
+ data: data.user
+ }
+ user = new Usergrid.Entity(options);
+ self.setToken(data.access_token);
+ self.set('email', data.user.email);
+
+
+ //delete next block and corresponding function when iframes are refactored
+ localStorage.setItem('accessToken', data.access_token);
+ localStorage.setItem('userUUID', data.user.uuid);
+ localStorage.setItem('userEmail', data.user.email);
+ //end delete block
+
+
+ organizations = data.user.organizations;
+ var org = '';
+ try {
+ //if we have an org stored, then use that one. Otherwise, use the first one.
+ var existingOrg = self.get('orgName');
+ org = (organizations[existingOrg]) ? organizations[existingOrg] :
+ organizations[Object.keys(organizations)[0]];
+ self.set('orgName', org.name);
+ } catch (e) {
+ err = true;
+ if (self.logging) {
+ console.log('error selecting org');
+ }
+ } //should always be an org
- //delete next block and corresponding function when iframes are refactored
- localStorage.setItem('accessToken', data.access_token);
- localStorage.setItem('userUUID', data.user.uuid);
- localStorage.setItem('userEmail', data.user.email);
- //end delete block
+ applications = self.parseApplicationsArray(org);
+ self.selectFirstApp(applications);
+ self.setObject('organizations', organizations);
+ self.setObject('applications', applications);
- organizations = data.user.organizations;
- var org = '';
- try {
- //if we have an org stored, then use that one. Otherwise, use the first one.
- var existingOrg = self.get('orgName');
- org = (organizations[existingOrg])?organizations[existingOrg]:organizations[Object.keys(organizations)[0]];
- self.set('orgName', org.name);
- } catch(e) {
- err = true;
- if (self.logging) { console.log('error selecting org'); }
- } //should always be an org
-
- applications = self.parseApplicationsArray(org);
- self.selectFirstApp(applications);
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data, user, organizations, applications);
+ }
+ });
+ }
- self.setObject('organizations', organizations);
- self.setObject('applications', applications);
+ Usergrid.Client.prototype.parseApplicationsArray = function(org) {
+ var applications = {};
+ for (var key in org.applications) {
+ var uuid = org.applications[key];
+ var name = key.split("/")[1];
+ applications[name] = ({
+ uuid: uuid,
+ name: name
+ });
}
- if (typeof(callback) === 'function') {
- callback(err, data, user, organizations, applications);
- }
- });
-}
-
-Usergrid.Client.prototype.parseApplicationsArray = function (org) {
- var applications = {};
- for (var key in org.applications) {
- var uuid = org.applications[key];
- var name = key.split("/")[1];
- applications[name] = ({uuid:uuid, name:name});
+ return applications;
}
- return applications;
-}
-
-Usergrid.Client.prototype.selectFirstApp = function (applications) {
- try {
- //try to select an app if one exists (will use existing if possible)
- var existingApp = this.get('appName');
- var firstApp = Object.keys(applications)[0];
- var appName = (applications[existingApp])?existingApp:Object.keys(applications)[0];
- this.set('appName', appName);
- } catch(e){}//may or may not be an application, if no, just fall through
- return appName;
-}
+ Usergrid.Client.prototype.selectFirstApp = function(applications) {
+ try {
+ //try to select an app if one exists (will use existing if possible)
+ var existingApp = this.get('appName');
+ var firstApp = Object.keys(applications)[0];
+ var appName = (applications[existingApp]) ? existingApp : Object.keys(
+ applications)[0];
+ this.set('appName', appName);
+ } catch (e) {} //may or may not be an application, if no, just fall through
+ return appName;
+ }
-Usergrid.Client.prototype.createApplication = function (name, callback) {
- var self = this;
- var options = {
- method:'POST',
- endpoint:'management/organizations/'+ this.get('orgName') + '/applications',
- mQuery:true,
- body:{name:name}
- };
- this.request(options, function(err, response) {
- var applications = {};
- if (err && self.logging) {
- console.log('error trying to create new application');
- if (typeof(callback) === 'function') {
- callback(err, applications);
+ Usergrid.Client.prototype.createApplication = function(name, callback) {
+ var self = this;
+ var options = {
+ method: 'POST',
+ endpoint: 'management/organizations/' + this.get('orgName') +
+ '/applications',
+ mQuery: true,
+ body: {
+ name: name
}
- } else {
- self.getApplications(callback);
- }
- });
-}
+ };
+ this.request(options, function(err, response) {
+ var applications = {};
+ if (err && self.logging) {
+ console.log('error trying to create new application');
+ if (typeof(callback) === 'function') {
+ callback(err, applications);
+ }
+ } else {
+ self.getApplications(callback);
+ }
+ });
+ }
-Usergrid.Client.prototype.getApplications = function(callback) {
- var self = this;
- var options = {
- method:'GET',
- endpoint:'management/organizations/'+this.get('orgName')+'/applications',
- mQuery:true
- };
- this.request(options, function(err, data) {
-/*
+ Usergrid.Client.prototype.getApplications = function(callback) {
+ var self = this;
+ var options = {
+ method: 'GET',
+ endpoint: 'management/organizations/' + this.get('orgName') +
+ '/applications',
+ mQuery: true
+ };
+ this.request(options, function(err, data) {
+ /*
//grab the applications
var applicationsData = data.data;
var applicationNames = self.keys(applicationsData).sort();
@@ -862,1571 +899,1609 @@ Usergrid.Client.prototype.getApplications = function(callback) {
count++;
} */
- applications = self.parseApplicationsArray({applications:data.data});
- self.selectFirstApp(applications);
- self.setObject('applications',applications);
-
- if(typeof(callback) === 'function') {
- callback(err, applications);
- }
- });
-}
-
-Usergrid.Client.prototype.getAdministrators = function (callback) {
- var self = this;
- var options = {
- method:'GET',
- endpoint:'management/organizations/'+this.get('orgName')+'/users',
- mQuery:true
- };
- this.request(options, function (err, data) {
- var administrators = [];
- if (err) {
+ applications = self.parseApplicationsArray({
+ applications: data.data
+ });
+ self.selectFirstApp(applications);
+ self.setObject('applications', applications);
- } else {
- var administrators = [];
- for(var i in data.data) {
- var admin = data.data[i];
- admin.image = self.getDisplayImage(admin.email, admin.picture);
- administrators.push(admin);
+ if (typeof(callback) === 'function') {
+ callback(err, applications);
}
- }
+ });
+ }
- if (typeof(callback) === 'function') {
- callback(err, administrators);
- }
- });
-}
+ Usergrid.Client.prototype.getAdministrators = function(callback) {
+ var self = this;
+ var options = {
+ method: 'GET',
+ endpoint: 'management/organizations/' + this.get('orgName') +
+ '/users',
+ mQuery: true
+ };
+ this.request(options, function(err, data) {
+ var administrators = [];
+ if (err) {
+ } else {
+ var administrators = [];
+ for (var i in data.data) {
+ var admin = data.data[i];
+ admin.image = self.getDisplayImage(admin.email, admin.picture);
+ administrators.push(admin);
+ }
+ }
-Usergrid.Client.prototype.createAdministrator = function (email, callback) {
- var self = this;
- var options = {
- method:'POST',
- endpoint:'management/organizations/'+ this.get('orgName') + '/users',
- mQuery:true,
- body:{email:email, password:''}
- };
- this.request(options, function(err, response) {
- var admins = {};
- if (err && self.logging) {
- console.log('error trying to create new administrator');
if (typeof(callback) === 'function') {
- callback(err, admins);
+ callback(err, administrators);
}
- } else {
- self.getAdministrators(callback);
- }
- });
-}
-
-
+ });
+ }
+ Usergrid.Client.prototype.createAdministrator = function(email, callback) {
+ var self = this;
+ var options = {
+ method: 'POST',
+ endpoint: 'management/organizations/' + this.get('orgName') +
+ '/users',
+ mQuery: true,
+ body: {
+ email: email,
+ password: ''
+ }
+ };
+ this.request(options, function(err, response) {
+ var admins = {};
+ if (err && self.logging) {
+ console.log('error trying to create new administrator');
+ if (typeof(callback) === 'function') {
+ callback(err, admins);
+ }
+ } else {
+ self.getAdministrators(callback);
+ }
+ });
+ }
-/*
-* 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)
-*/
-Usergrid.Client.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 Usergrid.Entity(options);
- self.setToken(data.access_token);
- }
- if (typeof(callback) === 'function') {
- callback(err, data, user);
- }
- });
-}
-/*
-* A public method to get the currently logged in user entity
-*
-* @method getLoggedInUser
-* @public
-* @param {function} callback
-* @return {callback} callback(err, data)
-*/
-Usergrid.Client.prototype.getLoggedInUser = function (callback) {
- if (!this.getToken()) {
- callback(true, null, null);
- } else {
+ /*
+ * 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)
+ */
+ Usergrid.Client.prototype.loginFacebook = function(facebookToken, callback) {
var self = this;
var options = {
- method:'GET',
- endpoint:'users/me'
+ method: 'GET',
+ endpoint: 'auth/facebook',
+ qs: {
+ fb_access_token: facebookToken
+ }
};
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);
- }
+ var user = {};
+ if (err && self.logging) {
+ console.log('error trying to log user in');
} else {
var options = {
- client:self,
- data:data.entities[0]
- }
- var user = new Usergrid.Entity(options);
- if (typeof(callback) === 'function') {
- callback(err, data, user);
+ client: self,
+ data: data.user
}
+ user = new Usergrid.Entity(options);
+ self.setToken(data.access_token);
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data, user);
}
});
}
-}
-/*
-* 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
-*/
-Usergrid.Client.prototype.isLoggedIn = function () {
- if (this.getToken()) {
- return true;
+ /*
+ * A public method to get the currently logged in user entity
+ *
+ * @method getLoggedInUser
+ * @public
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.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 Usergrid.Entity(options);
+ if (typeof(callback) === 'function') {
+ callback(err, data, user);
+ }
+ }
+ });
+ }
}
- return false;
-}
-/*
-* A public method to log out an app user - clears all user fields from client
-*
-* @method logout
-* @public
-* @return none
-*/
-Usergrid.Client.prototype.logout = function () {
- this.setToken(null);
- this.setObject('organizations', null);
- this.setObject('applications', null);
- this.set('orgName', null);
- this.set('appName', null);
- this.set('email', null);
- this.set("developerkey", null);
-}
+ /*
+ * 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
+ */
+ Usergrid.Client.prototype.isLoggedIn = function() {
+ if (this.getToken()) {
+ return true;
+ }
+ return false;
+ }
-/*
-* A private method to build the curl call to display on the command line
-*
-* @method buildCurlCall
-* @private
-* @param {object} options
-* @return {string} curl
-*/
-Usergrid.Client.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;
-}
-Usergrid.Client.prototype.getDisplayImage = function (email, picture, size) {
- try {
- if (picture) {
- return picture;
- }
- var size = size || 50;
- if (email.length) {
- return 'https://secure.gravatar.com/avatar/' + MD5(email) + '?s=' + size;
+ /*
+ * A public method to log out an app user - clears all user fields from client
+ *
+ * @method logout
+ * @public
+ * @return none
+ */
+ Usergrid.Client.prototype.logout = function() {
+ this.setToken(null);
+ this.setObject('organizations', null);
+ this.setObject('applications', null);
+ this.set('orgName', null);
+ this.set('appName', null);
+ this.set('email', null);
+ this.set("developerkey", null);
+ }
+
+ /*
+ * A private method to build the curl call to display on the command line
+ *
+ * @method buildCurlCall
+ * @private
+ * @param {object} options
+ * @return {string} curl
+ */
+ Usergrid.Client.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 {
- return 'https://apigee.com/usergrid/img/user_profile.png';
+ curl += ' -X GET';
}
- } catch(e) {
- return 'https://apigee.com/usergrid/img/user_profile.png';
- }
-}
-/*
-* A class to Model a Usergrid 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}}
-*/
-Usergrid.Entity = function(options) {
- if (options) {
- this._data = options.data || {};
- this._client = options.client || {};
+ //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;
+ }
+ Usergrid.Client.prototype.getDisplayImage = function(email, picture, size) {
+ try {
+ if (picture) {
+ return picture;
+ }
+ var size = size || 50;
+ if (email.length) {
+ return 'https://secure.gravatar.com/avatar/' + MD5(email) + '?s=' +
+ size;
+ } else {
+ return 'https://apigee.com/usergrid/img/user_profile.png';
+ }
+ } catch (e) {
+ return 'https://apigee.com/usergrid/img/user_profile.png';
+ }
}
-};
-/*
- * returns a serialized version of the entity object
- *
- * Note: use the client.restoreEntity() function to restore
- *
- * @method serialize
- * @return {string} data
- */
-Usergrid.Entity.prototype.serialize = function () {
- return JSON.stringify(this._data);
-}
+ /*
+ * A class to Model a Usergrid 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}}
+ */
+ Usergrid.Entity = function(options) {
+ if (options) {
+ this._data = options.data || {};
+ this._client = options.client || {};
+ }
+ };
-/*
-* 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
-*/
-Usergrid.Entity.prototype.get = function (field) {
- if (field) {
- return this._data[field];
- } else {
- return this._data;
+ /*
+ * returns a serialized version of the entity object
+ *
+ * Note: use the client.restoreEntity() function to restore
+ *
+ * @method serialize
+ * @return {string} data
+ */
+ Usergrid.Entity.prototype.serialize = function() {
+ return JSON.stringify(this._data);
}
-}
-/*
-* 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
-*/
-Usergrid.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];
+ /*
+ * 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
+ */
+ Usergrid.Entity.prototype.get = function(field) {
+ if (field) {
+ return this._data[field];
} else {
- this._data[key] = value;
+ return this._data;
}
- } else {
- this._data = {};
}
-}
-/*
-* Saves the entity back to the database
-*
-* @method save
-* @public
-* @param {function} callback
-* @return {callback} callback(err, data)
-*/
-Usergrid.Entity.prototype.save = function (callback) {
- var type = this.get('type');
- var method = 'POST';
- if (isUUID(this.get('uuid'))) {
- method = 'PUT';
- type += '/' + this.get('uuid');
- }
-
- //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);
+ /*
+ * 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
+ */
+ Usergrid.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 {
- if (retdata.entities) {
- if (retdata.entities.length) {
- var entity = retdata.entities[0];
- self.set(entity);
- //for connections, API returns type
- self.set('type', retdata.path);
- }
+ this._data = {};
+ }
+ }
+
+ /*
+ * Saves the entity back to the database
+ *
+ * @method save
+ * @public
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Entity.prototype.save = function(callback) {
+ var type = this.get('type');
+ var method = 'POST';
+ if (isUUID(this.get('uuid'))) {
+ method = 'PUT';
+ type += '/' + this.get('uuid');
+ }
+
+ //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;
}
- //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
+ 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);
}
- self._client.request(options, function (err, data) {
- if (err && self._client.logging) {
- console.log('could not update user');
+ } else {
+ if (retdata.entities) {
+ if (retdata.entities.length) {
+ var entity = retdata.entities[0];
+ self.set(entity);
+ //for connections, API returns type
+ self.set('type', retdata.path);
}
- //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);
+ }
+ //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
}
- });
- } else if (typeof(callback) === 'function') {
- callback(err, retdata, self);
+ 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);
+ }
}
- }
- });
-}
+ });
+ }
-/*
-* refreshes the entity by making a GET call back to the database
-*
-* @method fetch
-* @public
-* @param {function} callback
-* @return {callback} callback(err, data)
-*/
-Usergrid.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);
+ /*
+ * refreshes the entity by making a GET call back to the database
+ *
+ * @method fetch
+ * @public
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.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)
}
- return callback(true, {error:error}, self)
}
- }
- } else if (type === 'a path') {
+ } else if (type === 'a path') {
- ///TODO add code to deal with the type as 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);
+ 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)
}
- 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);
+ 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)
}
- 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);
+ }
+ });
}
- var options = {
- method:'GET',
- endpoint:type
- };
- this._client.request(options, function (err, data) {
- if (err && self._client.logging) {
- console.log('could not get entity');
+
+ /*
+ * 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)
+ *
+ */
+ Usergrid.Entity.prototype.destroy = function(callback) {
+ var type = this.get('type');
+ if (isUUID(this.get('uuid'))) {
+ type += '/' + this.get('uuid');
} 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') {
+ var error = 'Error trying to delete object - no uuid specified.';
+ if (self._client.logging) {
+ console.log(error);
}
+ callback(true, error);
}
}
- if (typeof(callback) === 'function') {
- callback(err, data, self);
- }
- });
-}
-
-/*
-* 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)
-*
-*/
-Usergrid.Entity.prototype.destroy = function (callback) {
- var type = this.get('type');
- if (isUUID(this.get('uuid'))) {
- type += '/' + this.get('uuid');
- } else {
- if (typeof(callback) === 'function') {
- var error = 'Error trying to delete object - no uuid specified.';
- if (self._client.logging) {
- console.log(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);
}
- callback(true, error);
- }
+ if (typeof(callback) === 'function') {
+ callback(err, data);
+ }
+ });
}
- 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);
- }
- });
-}
-/*
-* connects one entity to another
-*
-* @method connect
-* @public
-* @param {string} connection
-* @param {object} entity
-* @param {function} callback
-* @return {callback} callback(err, data)
-*
-*/
-Usergrid.Entity.prototype.connect = function (connection, entity, callback) {
+ /*
+ * connects one entity to another
+ *
+ * @method connect
+ * @public
+ * @param {string} connection
+ * @param {object} entity
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ *
+ */
+ Usergrid.Entity.prototype.connect = function(connection, entity, callback) {
- var self = this;
+ 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);
+ //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);
}
- callback(true, error);
+ return;
}
- 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);
+ //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);
}
- callback(true, error);
+ return;
}
- 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);
- }
- });
-}
+ 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);
+ }
+ });
+ }
-/*
-* returns a unique identifier for an entity
-*
-* @method connect
-* @public
-* @param {object} entity
-* @param {function} callback
-* @return {callback} callback(err, data)
-*
-*/
-Usergrid.Entity.prototype.getEntityId = function (entity) {
- var id = false;
- if (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');
+ /*
+ * returns a unique identifier for an entity
+ *
+ * @method connect
+ * @public
+ * @param {object} entity
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ *
+ */
+ Usergrid.Entity.prototype.getEntityId = function(entity) {
+ var id = false;
+ if (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;
}
- return id;
-}
-/*
-* gets an entities connections
-*
-* @method getConnections
-* @public
-* @param {string} connection
-* @param {object} entity
-* @param {function} callback
-* @return {callback} callback(err, data, connections)
-*
-*/
-Usergrid.Entity.prototype.getConnections = function (connection, callback) {
+ /*
+ * gets an entities connections
+ *
+ * @method getConnections
+ * @public
+ * @param {string} connection
+ * @param {object} entity
+ * @param {function} callback
+ * @return {callback} callback(err, data, connections)
+ *
+ */
+ Usergrid.Entity.prototype.getConnections = function(connection, callback) {
- var self = this;
+ 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);
+ //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);
}
- callback(true, error);
+ return;
}
- 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');
- }
+ 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] = {};
+ 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]
+ 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);
- }
- });
+ if (typeof(callback) === 'function') {
+ callback(err, data, data.entities);
+ }
+ });
-}
+ }
-Usergrid.Entity.prototype.getGroups = function (callback) {
+ Usergrid.Entity.prototype.getGroups = function(callback) {
- var self = this;
+ var self = this;
- var endpoint = 'users' + '/' + this.get('uuid') + '/groups' ;
- 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');
- }
+ var endpoint = 'users' + '/' + this.get('uuid') + '/groups';
+ 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['groups'] = data.entities;
+ self['groups'] = data.entities;
- if (typeof(callback) === 'function') {
- callback(err, data, data.entities);
- }
- });
+ if (typeof(callback) === 'function') {
+ callback(err, data, data.entities);
+ }
+ });
-}
+ }
-Usergrid.Entity.prototype.getActivities = function (callback) {
+ Usergrid.Entity.prototype.getActivities = function(callback) {
- var self = this;
+ var self = this;
- var endpoint = this.get('type') + '/' + this.get('uuid') + '/activities' ;
- 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');
- }
+ var endpoint = this.get('type') + '/' + this.get('uuid') + '/activities';
+ 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');
+ }
- for(entity in data.entities) {
- data.entities[entity].createdDate = (new Date(data.entities[entity].created)).toUTCString();
- }
+ for (entity in data.entities) {
+ data.entities[entity].createdDate = (new Date(data.entities[entity]
+ .created)).toUTCString();
+ }
- self['activities'] = data.entities;
+ self['activities'] = data.entities;
- if (typeof(callback) === 'function') {
- callback(err, data, data.entities);
- }
- });
+ if (typeof(callback) === 'function') {
+ callback(err, data, data.entities);
+ }
+ });
+
+ }
-}
+ Usergrid.Entity.prototype.getFollowing = function(callback) {
-Usergrid.Entity.prototype.getFollowing = function (callback) {
+ var self = this;
- var self = this;
+ var endpoint = 'users' + '/' + this.get('uuid') + '/following';
+ var options = {
+ method: 'GET',
+ endpoint: endpoint
+ };
+ this._client.request(options, function(err, data) {
+ if (err && self._client.logging) {
+ console.log('could not get user following');
+ }
- var endpoint = 'users' + '/' + this.get('uuid') + '/following' ;
- var options = {
- method:'GET',
- endpoint:endpoint
- };
- this._client.request(options, function (err, data) {
- if (err && self._client.logging) {
- console.log('could not get user following');
- }
+ for (entity in data.entities) {
+ data.entities[entity].createdDate = (new Date(data.entities[entity]
+ .created)).toUTCString();
+ var image = self._client.getDisplayImage(data.entities[entity].email,
+ data.entities[entity].picture);
+ data.entities[entity]._portal_image_icon = image;
+ }
- for(entity in data.entities) {
- data.entities[entity].createdDate = (new Date(data.entities[entity].created)).toUTCString();
- var image = self._client.getDisplayImage(data.entities[entity].email, data.entities[entity].picture);
- data.entities[entity]._portal_image_icon = image;
- }
+ self['following'] = data.entities;
- self['following'] = data.entities;
+ if (typeof(callback) === 'function') {
+ callback(err, data, data.entities);
+ }
+ });
- if (typeof(callback) === 'function') {
- callback(err, data, data.entities);
- }
- });
+ }
-}
+ Usergrid.Entity.prototype.getFollowers = function(callback) {
-Usergrid.Entity.prototype.getFollowers = function (callback) {
+ var self = this;
- var self = this;
+ var endpoint = 'users' + '/' + this.get('uuid') + '/followers';
+ var options = {
+ method: 'GET',
+ endpoint: endpoint
+ };
+ this._client.request(options, function(err, data) {
+ if (err && self._client.logging) {
+ console.log('could not get user followers');
+ }
- var endpoint = 'users' + '/' + this.get('uuid') + '/followers' ;
- var options = {
- method:'GET',
- endpoint:endpoint
- };
- this._client.request(options, function (err, data) {
- if (err && self._client.logging) {
- console.log('could not get user followers');
- }
+ for (entity in data.entities) {
+ data.entities[entity].createdDate = (new Date(data.entities[entity]
+ .created)).toUTCString();
+ var image = self._client.getDisplayImage(data.entities[entity].email,
+ data.entities[entity].picture);
+ data.entities[entity]._portal_image_icon = image;
+ }
- for(entity in data.entities) {
- data.entities[entity].createdDate = (new Date(data.entities[entity].created)).toUTCString();
- var image = self._client.getDisplayImage(data.entities[entity].email, data.entities[entity].picture);
- data.entities[entity]._portal_image_icon = image;
- }
+ self['followers'] = data.entities;
- self['followers'] = data.entities;
+ if (typeof(callback) === 'function') {
+ callback(err, data, data.entities);
+ }
+ });
- if (typeof(callback) === 'function') {
- callback(err, data, data.entities);
- }
- });
+ }
-}
+ Usergrid.Entity.prototype.getRoles = function(callback) {
-Usergrid.Entity.pr
<TRUNCATED>
[2/2] git commit: fix create collections
Posted by sf...@apache.org.
fix create collections
Project: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/commit/d972699b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/tree/d972699b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-usergrid/diff/d972699b
Branch: refs/heads/two-dot-o-candidate
Commit: d972699b570658ac09604f5a09f235912b2dde23
Parents: e0f7b49
Author: Shawn Feldman <sf...@apache.org>
Authored: Wed Sep 24 13:38:40 2014 -0600
Committer: Shawn Feldman <sf...@apache.org>
Committed: Wed Sep 24 13:38:40 2014 -0600
----------------------------------------------------------------------
portal/js/global/ug-service.js | 1097 +++++----
portal/js/libs/usergrid.sdk.js | 4264 ++++++++++++++++++-----------------
2 files changed, 2792 insertions(+), 2569 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/d972699b/portal/js/global/ug-service.js
----------------------------------------------------------------------
diff --git a/portal/js/global/ug-service.js b/portal/js/global/ug-service.js
index 1822cf9..db2bfe9 100644
--- a/portal/js/global/ug-service.js
+++ b/portal/js/global/ug-service.js
@@ -18,28 +18,30 @@
*/
'use strict';
-AppServices.Services.factory('ug', function (configuration, $rootScope,utility, $q, $http, $resource, $log,$location) {
+AppServices.Services.factory('ug', function(configuration, $rootScope, utility,
+ $q, $http, $resource, $log, $location) {
var requestTimes = [],
running = false,
currentRequests = {};
- function reportError(data,config){
- console.error(data)
+ function reportError(data, config) {
+ console.error(data)
};
- var getAccessToken = function(){
+ var getAccessToken = function() {
return sessionStorage.getItem('accessToken');
};
return {
- get:function(prop,isObject){
- return isObject ? this.client().getObject(prop) : this.client().get(prop);
+ get: function(prop, isObject) {
+ return isObject ? this.client().getObject(prop) : this.client().get(
+ prop);
},
- set:function(prop,value){
- this.client().set(prop,value);
+ set: function(prop, value) {
+ this.client().set(prop, value);
},
- getUrls: function(qs){
+ getUrls: function(qs) {
var host = $location.host();
var BASE_URL = '';
var DATA_URL = '';
@@ -49,103 +51,126 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
//development
DATA_URL = 'https://api.usergrid.com';
break;
- default :
+ default:
DATA_URL = Usergrid.overrideUrl;
break;
}
//override with querystring
DATA_URL = qs.api_url || DATA_URL;
- DATA_URL = DATA_URL.lastIndexOf('/') === DATA_URL.length - 1 ? DATA_URL.substring(0,DATA_URL.length-1) : DATA_URL;
+ DATA_URL = DATA_URL.lastIndexOf('/') === DATA_URL.length - 1 ? DATA_URL
+ .substring(0, DATA_URL.length - 1) : DATA_URL;
return {
DATA_URL: DATA_URL,
LOGIN_URL: BASE_URL + '/accounts/sign_in',
PROFILE_URL: BASE_URL + '/accounts/my_account',
LOGOUT_URL: BASE_URL + '/accounts/sign_out',
apiUrl: DATA_URL,
- use_sso:use_sso
+ use_sso: use_sso
};
},
- orgLogin:function(username,password){
+ orgLogin: function(username, password) {
var self = this;
this.client().set('email', username);
this.client().set('token', null);
- this.client().orgLogin(username,password,function(err, data, user, organizations, applications){
- if(err){
- $rootScope.$broadcast('loginFailed', err,data);
- }else{
- self.initializeCurrentUser(function () {
- $rootScope.$broadcast('loginSuccesful', user, organizations, applications);
+ this.client().orgLogin(username, password, function(err, data, user,
+ organizations, applications) {
+ if (err) {
+ $rootScope.$broadcast('loginFailed', err, data);
+ } else {
+ self.initializeCurrentUser(function() {
+ $rootScope.$broadcast('loginSuccesful', user, organizations,
+ applications);
});
}
});
},
- checkAuthentication:function(force){
+ checkAuthentication: function(force) {
var ug = this;
var client = ug.client();
- var initialize = function () {
- ug.initializeCurrentUser(function () {
- $rootScope.userEmail = client.get('email');
- $rootScope.organizations = client.getObject('organizations');
- $rootScope.applications = client.getObject('applications');
- $rootScope.currentOrg = client.get('orgName');
- $rootScope.currentApp = client.get('appName');
- var size = 0, key;
- for (key in $rootScope.applications) {
- if ($rootScope.applications.hasOwnProperty(key)) size++;
- }
- $rootScope.$broadcast('checkAuthentication-success', client.getObject('organizations'), client.getObject('applications'), client.get('orgName'), client.get('appName'), client.get('email'));
- });
- },
- isAuthenticated = function () {
- var authenticated = client.get('token') !== null && client.get('organizations') !== null;
- if (authenticated) {
- initialize();
+ var initialize = function() {
+ ug.initializeCurrentUser(function() {
+ $rootScope.userEmail = client.get('email');
+ $rootScope.organizations = client.getObject('organizations');
+ $rootScope.applications = client.getObject('applications');
+ $rootScope.currentOrg = client.get('orgName');
+ $rootScope.currentApp = client.get('appName');
+ var size = 0,
+ key;
+ for (key in $rootScope.applications) {
+ if ($rootScope.applications.hasOwnProperty(key)) size++;
}
- return authenticated;
- };
- if(!isAuthenticated() || force){
- if(!client.get('token')){
- return $rootScope.$broadcast('checkAuthentication-error','no token',{},client.get('email'));
+ $rootScope.$broadcast('checkAuthentication-success', client.getObject(
+ 'organizations'), client.getObject('applications'), client.get(
+ 'orgName'), client.get('appName'), client.get('email'));
+ });
+ },
+ isAuthenticated = function() {
+ var authenticated = client.get('token') !== null && client.get(
+ 'organizations') !== null;
+ if (authenticated) {
+ initialize();
+ }
+ return authenticated;
+ };
+ if (!isAuthenticated() || force) {
+ if (!client.get('token')) {
+ return $rootScope.$broadcast('checkAuthentication-error',
+ 'no token', {}, client.get('email'));
}
- this.client().reAuthenticateLite(function(err){
- var missingData = err || ( !client.get('orgName') || !client.get('appName') || !client.getObject('organizations') || !client.getObject('applications'));
- var email = client.get('email');
- if(err || missingData){
- $rootScope.$broadcast('checkAuthentication-error',err,missingData,email);
- }else{
+ this.client().reAuthenticateLite(function(err) {
+ var missingData = err || (!client.get('orgName') || !client.get(
+ 'appName') || !client.getObject('organizations') || !client
+ .getObject('applications'));
+ var email = client.get('email');
+ if (err || missingData) {
+ $rootScope.$broadcast('checkAuthentication-error', err,
+ missingData, email);
+ } else {
initialize();
}
});
}
},
- reAuthenticate:function(email,eventOveride){
+ reAuthenticate: function(email, eventOveride) {
var ug = this;
- this.client().reAuthenticate(email,function(err, data, user, organizations, applications){
- if(!err){
+ this.client().reAuthenticate(email, function(err, data, user,
+ organizations, applications) {
+ if (!err) {
$rootScope.currentUser = user;
}
- if(!err){
+ if (!err) {
$rootScope.userEmail = user.get('email');
$rootScope.organizations = organizations;
$rootScope.applications = applications;
$rootScope.currentOrg = ug.get('orgName');
$rootScope.currentApp = ug.get('appName');
$rootScope.currentUser = user._data;
- $rootScope.currentUser.profileImg = utility.get_gravatar($rootScope.currentUser.email);
+ $rootScope.currentUser.profileImg = utility.get_gravatar(
+ $rootScope.currentUser.email);
}
- $rootScope.$broadcast((eventOveride || 'reAuthenticate')+'-' + (err ? 'error' : 'success'),err, data, user, organizations, applications);
+ $rootScope.$broadcast((eventOveride || 'reAuthenticate') + '-' + (
+ err ? 'error' : 'success'), err, data, user, organizations,
+ applications);
});
},
logoutCallback: function() {
$rootScope.$broadcast('userNotAuthenticated');
},
- logout:function(){
+ logout: function() {
$rootScope.activeUI = false;
$rootScope.userEmail = 'user@apigee.com';
- $rootScope.organizations = {"noOrg":{name:"No Orgs Found"}};
- $rootScope.applications = {"noApp":{name:"No Apps Found"}};
+ $rootScope.organizations = {
+ "noOrg": {
+ name: "No Orgs Found"
+ }
+ };
+ $rootScope.applications = {
+ "noApp": {
+ name: "No Apps Found"
+ }
+ };
$rootScope.currentOrg = 'No Org Found';
$rootScope.currentApp = 'No App Found';
sessionStorage.setItem('accessToken', null);
@@ -155,38 +180,39 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
this.client().logout();
this._client = null;
},
- client: function(){
+ client: function() {
var options = {
- buildCurl:true,
- logging:true
+ buildCurl: true,
+ logging: true
};
- if(Usergrid.options && Usergrid.options.client){
+ if (Usergrid.options && Usergrid.options.client) {
options.keys = Usergrid.options.client;
}
this._client = this._client || new Usergrid.Client(options,
- $rootScope.urls().DATA_URL
+ $rootScope.urls().DATA_URL
);
return this._client;
},
- setClientProperty:function(key,value){
+ setClientProperty: function(key, value) {
this.client().set(key, value);
},
- getTopCollections: function () {
+ getTopCollections: function() {
var options = {
- method:'GET',
+ method: 'GET',
endpoint: ''
}
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error getting collections');
+ $rootScope.$broadcast('alert', 'error',
+ 'error getting collections');
} else {
var collections = data.entities[0].metadata.collections;
$rootScope.$broadcast('top-collections-received', collections);
}
});
},
- createCollection: function (collectionName) {
+ createCollection: function(collectionName) {
var collections = {};
collections[collectionName] = {};
var metadata = {
@@ -195,84 +221,121 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
}
var options = {
- method:'PUT',
+ method: 'PUT',
body: metadata,
endpoint: ''
}
- this.client().request(options, function (err, data) {
+ var self = this;
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error creating collection');
- } else {
- $rootScope.$broadcast('collection-created', collections);
+ console.error(err);
+ return $rootScope.$broadcast('alert', 'error',
+ 'error creating collection');
}
+ self.client().createEntity({
+ type: collectionName,
+ testData: 'test'
+ }, function(err, entity) {
+ if (err) {
+ console.error(err);
+ return $rootScope.$broadcast('alert', 'error',
+ 'error creating collection');
+ }
+ entity.destroy(function() {
+ self.getTopCollections(function(err, collections) {
+ if (err) {
+ $rootScope.$broadcast('alert', 'error',
+ 'error creating collection');
+ } else {
+ $rootScope.$broadcast('collection-created',
+ collections);
+ }
+ });
+ });
+
+ })
+
+
});
},
- getApplications: function () {
- this.client().getApplications(function (err, applications) {
+ getApplications: function() {
+ this.client().getApplications(function(err, applications) {
if (err) {
- applications && console.error(applications);
- }else{
+ applications && console.error(applications);
+ } else {
$rootScope.$broadcast('applications-received', applications);
}
});
},
- getAdministrators: function () {
- this.client().getAdministrators(function (err, administrators) {
+ getAdministrators: function() {
+ this.client().getAdministrators(function(err, administrators) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error getting administrators');
+ $rootScope.$broadcast('alert', 'error',
+ 'error getting administrators');
}
$rootScope.$broadcast('administrators-received', administrators);
});
},
- createApplication: function (appName) {
- this.client().createApplication(appName, function (err, applications) {
+ createApplication: function(appName) {
+ this.client().createApplication(appName, function(err, applications) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error creating application');
- }else{
- $rootScope.$broadcast('applications-created', applications,appName);
+ $rootScope.$broadcast('alert', 'error',
+ 'error creating application');
+ } else {
+ $rootScope.$broadcast('applications-created', applications,
+ appName);
$rootScope.$broadcast('applications-received', applications);
}
});
},
- createAdministrator: function (adminName) {
- this.client().createAdministrator(adminName, function (err, administrators) {
+ createAdministrator: function(adminName) {
+ this.client().createAdministrator(adminName, function(err,
+ administrators) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error creating administrator');
+ $rootScope.$broadcast('alert', 'error',
+ 'error creating administrator');
}
$rootScope.$broadcast('administrators-received', administrators);
});
},
- getFeed: function () {
+ getFeed: function() {
var options = {
- method:'GET',
- endpoint:'management/organizations/'+this.client().get('orgName')+'/feed',
- mQuery:true
+ method: 'GET',
+ endpoint: 'management/organizations/' + this.client().get('orgName') +
+ '/feed',
+ mQuery: true
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error getting feed');
} else {
var feedData = data.entities;
var feed = [];
- var i=0;
- for (i=0; i < feedData.length; i++) {
+ var i = 0;
+ for (i = 0; i < feedData.length; i++) {
var date = (new Date(feedData[i].created)).toUTCString();
var title = feedData[i].title;
- var n=title.indexOf(">");
- title = title.substring(n+1,title.length);
+ var n = title.indexOf(">");
+ title = title.substring(n + 1, title.length);
- n=title.indexOf(">");
- title = title.substring(n+1,title.length);
+ n = title.indexOf(">");
+ title = title.substring(n + 1, title.length);
if (feedData[i].actor) {
title = feedData[i].actor.displayName + ' ' + title;
}
- feed.push({date:date, title:title});
+ feed.push({
+ date: date,
+ title: title
+ });
}
if (i === 0) {
- feed.push({date:"", title:"No Activities found."});
+ feed.push({
+ date: "",
+ title: "No Activities found."
+ });
}
$rootScope.$broadcast('feed-received', feed);
@@ -280,13 +343,13 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
});
},
- createGroup: function (path, title) {
+ createGroup: function(path, title) {
var options = {
- path:path,
- title:title
+ path: path,
+ title: title
}
var self = this;
- this.groupsCollection.addEntity(options, function(err){
+ this.groupsCollection.addEntity(options, function(err) {
if (err) {
$rootScope.$broadcast('groups-create-error', err);
} else {
@@ -295,13 +358,13 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
});
},
- createRole: function (name, title) {
+ createRole: function(name, title) {
var options = {
- name:name,
- title:title
- },
- self = this;
- this.rolesCollection.addEntity(options, function(err){
+ name: name,
+ title: title
+ },
+ self = this;
+ this.rolesCollection.addEntity(options, function(err) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error creating role');
} else {
@@ -309,20 +372,22 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
});
},
- createUser: function (username, name, email, password){
+ createUser: function(username, name, email, password) {
var options = {
- username:username,
- name:name,
- email:email,
- password:password
+ username: username,
+ name: name,
+ email: email,
+ password: password
}
var self = this;
- this.usersCollection.addEntity(options, function(err, data){
+ this.usersCollection.addEntity(options, function(err, data) {
if (err) {
if (typeof data === 'string') {
$rootScope.$broadcast("alert", "error", "error: " + data);
} else {
- $rootScope.$broadcast("alert", "error", "error creating user. the email address might already exist.");
+ $rootScope.$broadcast("alert", "error",
+ "error creating user. the email address might already exist."
+ );
}
} else {
$rootScope.$broadcast('users-create-success', self.usersCollection);
@@ -331,10 +396,10 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
});
},
- getCollection: function (type, path, orderBy, query, limit) {
+ getCollection: function(type, path, orderBy, query, limit) {
var options = {
- type:path,
- qs:{}
+ type: path,
+ qs: {}
}
if (query) {
options.qs['ql'] = query;
@@ -342,7 +407,8 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
//force order by 'created desc' if none exists
if (options.qs.ql) {
- options.qs['ql'] = options.qs.ql + ' order by ' + (orderBy || 'created desc');
+ options.qs['ql'] = options.qs.ql + ' order by ' + (orderBy ||
+ 'created desc');
} else {
options.qs['ql'] = ' order by ' + (orderBy || 'created desc');
}
@@ -350,38 +416,40 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
if (limit) {
options.qs['limit'] = limit;
}
- this.client().createCollection(options, function (err, collection, data) {
+ this.client().createCollection(options, function(err, collection, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error getting ' + collection._type + ': ' + data.error_description);
+ $rootScope.$broadcast('alert', 'error', 'error getting ' +
+ collection._type + ': ' + data.error_description);
$rootScope.$broadcast(type + '-error', collection);
} else {
$rootScope.$broadcast(type + '-received', collection);
}
//temporarily adding scope.apply to get working in prod, otherwise the events won't get broadcast
//todo - we need an apply strategy for 3rd party ug calls!
- if(!$rootScope.$$phase) {
+ if (!$rootScope.$$phase) {
$rootScope.$apply();
}
});
},
- runDataQuery: function (queryPath, searchString, queryLimit) {
+ runDataQuery: function(queryPath, searchString, queryLimit) {
this.getCollection('query', queryPath, null, searchString, queryLimit);
},
runDataPOSTQuery: function(queryPath, body) {
var self = this;
var options = {
- method:'POST',
- endpoint:queryPath,
- body:body
+ method: 'POST',
+ endpoint: queryPath,
+ body: body
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error: ' + data.error_description);
- $rootScope.$broadcast('error-running-query', data);
+ $rootScope.$broadcast('error-running-query', data);
} else {
var queryPath = data.path;
- self.getCollection('query', queryPath, null, 'order by modified DESC', null);
+ self.getCollection('query', queryPath, null,
+ 'order by modified DESC', null);
}
});
@@ -389,9 +457,9 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
runDataPutQuery: function(queryPath, searchString, queryLimit, body) {
var self = this;
var options = {
- method:'PUT',
- endpoint:queryPath,
- body:body
+ method: 'PUT',
+ endpoint: queryPath,
+ body: body
};
if (searchString) {
@@ -401,13 +469,14 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
options.qs['queryLimit'] = queryLimit;
}
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error: ' + data.error_description);
} else {
var queryPath = data.path;
- self.getCollection('query', queryPath, null, 'order by modified DESC', null);
+ self.getCollection('query', queryPath, null,
+ 'order by modified DESC', null);
}
});
@@ -415,8 +484,8 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
runDataDeleteQuery: function(queryPath, searchString, queryLimit) {
var self = this;
var options = {
- method:'DELETE',
- endpoint:queryPath
+ method: 'DELETE',
+ endpoint: queryPath
};
if (searchString) {
@@ -426,74 +495,79 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
options.qs['queryLimit'] = queryLimit;
}
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error: ' + data.error_description);
} else {
var queryPath = data.path;
- self.getCollection('query', queryPath, null, 'order by modified DESC', null);
+ self.getCollection('query', queryPath, null,
+ 'order by modified DESC', null);
}
});
},
- getUsers: function () {
- this.getCollection('users','users','username');
+ getUsers: function() {
+ this.getCollection('users', 'users', 'username');
var self = this;
- $rootScope.$on("users-received",function(evt, users){
+ $rootScope.$on("users-received", function(evt, users) {
self.usersCollection = users;
})
},
- getGroups: function () {
- this.getCollection('groups','groups','title');
+ getGroups: function() {
+ this.getCollection('groups', 'groups', 'title');
var self = this;
$rootScope.$on('groups-received', function(event, roles) {
self.groupsCollection = roles;
});
- },
- getRoles: function () {
- this.getCollection('roles','roles','name');
+ },
+ getRoles: function() {
+ this.getCollection('roles', 'roles', 'name');
var self = this;
$rootScope.$on('roles-received', function(event, roles) {
self.rolesCollection = roles
});
},
- getNotifiers: function () {
+ getNotifiers: function() {
var query = '',
- limit = '100',
- self = this;
- this.getCollection('notifiers','notifiers','created', query, limit);
+ limit = '100',
+ self = this;
+ this.getCollection('notifiers', 'notifiers', 'created', query, limit);
$rootScope.$on('notifiers-received', function(event, notifiers) {
self.notifiersCollection = notifiers;
});
},
- getNotificationHistory: function (type) {
+ getNotificationHistory: function(type) {
var query = null;
if (type) {
query = "select * where state = '" + type + "'";
}
- this.getCollection('notifications','notifications', 'created desc', query);
+ this.getCollection('notifications', 'notifications', 'created desc',
+ query);
var self = this;
$rootScope.$on('notifications-received', function(event, notifications) {
self.notificationCollection = notifications;
});
},
- getNotificationReceipts: function (uuid) {
- this.getCollection('receipts', 'notifications/'+uuid+'/receipts');
+ getNotificationReceipts: function(uuid) {
+ this.getCollection('receipts', 'notifications/' + uuid + '/receipts');
var self = this;
$rootScope.$on('receipts-received', function(event, receipts) {
self.receiptsCollection = receipts;
});
},
- getIndexes: function (path) {
+ getIndexes: function(path) {
var options = {
- method:'GET',
- endpoint: path.split('/').concat('indexes').filter(function(bit){return bit && bit.length}).join('/')
+ method: 'GET',
+ endpoint: path.split('/').concat('indexes').filter(function(bit) {
+ return bit && bit.length
+ }).join('/')
}
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'Problem getting indexes: ' + data.error);
+ $rootScope.$broadcast('alert', 'error',
+ 'Problem getting indexes: ' + data.error);
} else {
$rootScope.$broadcast('indexes-received', data.data);
}
@@ -501,25 +575,28 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
},
sendNotification: function(path, body) {
var options = {
- method:'POST',
+ method: 'POST',
endpoint: path,
- body:body
+ body: body
}
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'Problem creating notification: ' + data.error);
+ $rootScope.$broadcast('alert', 'error',
+ 'Problem creating notification: ' + data.error);
} else {
$rootScope.$broadcast('send-notification-complete');
}
});
},
- getRolesUsers: function (username) {
+ getRolesUsers: function(username) {
var self = this;
var options = {
- type:'roles/users/'+username,
- qs:{ql:'order by username'}
+ type: 'roles/users/' + username,
+ qs: {
+ ql: 'order by username'
+ }
}
- this.client().createCollection(options, function (err, users) {
+ this.client().createCollection(options, function(err, users) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error getting users');
} else {
@@ -528,49 +605,51 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
});
},
- getTypeAheadData: function (type, searchString, searchBy, orderBy) {
+ getTypeAheadData: function(type, searchString, searchBy, orderBy) {
var self = this;
var search = '';
- var qs = {limit: 100};
+ var qs = {
+ limit: 100
+ };
if (searchString) {
- search = "select * where "+searchBy+" = '"+searchString+"'";
+ search = "select * where " + searchBy + " = '" + searchString + "'";
}
if (orderBy) {
- search = search + " order by "+orderBy;
+ search = search + " order by " + orderBy;
}
if (search) {
qs.ql = search;
}
var options = {
- method:'GET',
+ method: 'GET',
endpoint: type,
- qs:qs
+ qs: qs
}
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error getting '+type);
+ $rootScope.$broadcast('alert', 'error', 'error getting ' + type);
} else {
var entities = data.entities;
- $rootScope.$broadcast(type +'-typeahead-received', entities);
+ $rootScope.$broadcast(type + '-typeahead-received', entities);
}
});
},
- getUsersTypeAhead: function (searchString) {
+ getUsersTypeAhead: function(searchString) {
this.getTypeAheadData('users', searchString, 'username', 'username');
},
- getGroupsTypeAhead: function (searchString) {
+ getGroupsTypeAhead: function(searchString) {
this.getTypeAheadData('groups', searchString, 'path', 'path');
},
- getRolesTypeAhead: function (searchString) {
+ getRolesTypeAhead: function(searchString) {
this.getTypeAheadData('roles', searchString, 'name', 'name');
},
- getGroupsForUser: function (user) {
+ getGroupsForUser: function(user) {
var self = this;
var options = {
- type:'users/'+user+'/groups'
+ type: 'users/' + user + '/groups'
}
- this.client().createCollection(options, function (err, groups) {
+ this.client().createCollection(options, function(err, groups) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error getting groups');
} else {
@@ -580,53 +659,56 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
});
},
- addUserToGroup: function (user, group) {
+ addUserToGroup: function(user, group) {
var self = this;
var options = {
- type:'users/'+user+'/groups/'+group
+ type: 'users/' + user + '/groups/' + group
}
- this.client().createEntity(options, function (err, entity) {
+ this.client().createEntity(options, function(err, entity) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error adding user to group');
+ $rootScope.$broadcast('alert', 'error',
+ 'error adding user to group');
} else {
$rootScope.$broadcast('user-added-to-group-received');
}
});
},
- addUserToRole: function (user, role) {
+ addUserToRole: function(user, role) {
var options = {
- method:'POST',
- endpoint:'roles/'+role+'/users/'+user
+ method: 'POST',
+ endpoint: 'roles/' + role + '/users/' + user
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error adding user to role');
+ $rootScope.$broadcast('alert', 'error',
+ 'error adding user to role');
} else {
$rootScope.$broadcast('role-update-received');
}
});
},
- addGroupToRole: function (group, role) {
+ addGroupToRole: function(group, role) {
var options = {
- method:'POST',
- endpoint:'roles/'+role+'/groups/'+group
+ method: 'POST',
+ endpoint: 'roles/' + role + '/groups/' + group
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error adding group to role');
+ $rootScope.$broadcast('alert', 'error',
+ 'error adding group to role');
} else {
$rootScope.$broadcast('role-update-received');
}
});
},
- followUser: function (user) {
+ followUser: function(user) {
var self = this;
- var username = $rootScope.selectedUser.get('uuid');
+ var username = $rootScope.selectedUser.get('uuid');
var options = {
- method:'POST',
- endpoint:'users/'+username+'/following/users/'+user
+ method: 'POST',
+ endpoint: 'users/' + username + '/following/users/' + user
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error following user');
} else {
@@ -634,13 +716,15 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
});
},
- newPermission: function (permission, type, entity) { //"get,post,put:/mypermission"
+ newPermission: function(permission, type, entity) { //"get,post,put:/mypermission"
var options = {
- method:'POST',
- endpoint:type+'/'+entity+'/permissions',
- body:{"permission":permission}
+ method: 'POST',
+ endpoint: type + '/' + entity + '/permissions',
+ body: {
+ "permission": permission
+ }
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error adding permission');
} else {
@@ -648,119 +732,133 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
}
});
},
- newUserPermission: function (permission, username) {
- this.newPermission(permission,'users',username)
+ newUserPermission: function(permission, username) {
+ this.newPermission(permission, 'users', username)
},
- newGroupPermission: function (permission, path) {
- this.newPermission(permission,'groups',path)
+ newGroupPermission: function(permission, path) {
+ this.newPermission(permission, 'groups', path)
},
- newRolePermission: function (permission, name) {
- this.newPermission(permission,'roles',name)
+ newRolePermission: function(permission, name) {
+ this.newPermission(permission, 'roles', name)
},
- deletePermission: function (permission, type, entity) { //"get,post,put:/mypermission"
+ deletePermission: function(permission, type, entity) { //"get,post,put:/mypermission"
var options = {
- method:'DELETE',
- endpoint:type+'/'+entity+'/permissions',
- qs:{permission:permission}
+ method: 'DELETE',
+ endpoint: type + '/' + entity + '/permissions',
+ qs: {
+ permission: permission
+ }
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error deleting permission');
+ $rootScope.$broadcast('alert', 'error',
+ 'error deleting permission');
} else {
$rootScope.$broadcast('permission-update-received');
}
});
},
- deleteUserPermission: function (permission, user) {
- this.deletePermission(permission,'users',user);
+ deleteUserPermission: function(permission, user) {
+ this.deletePermission(permission, 'users', user);
},
- deleteGroupPermission: function (permission, group) {
- this.deletePermission(permission,'groups',group);
+ deleteGroupPermission: function(permission, group) {
+ this.deletePermission(permission, 'groups', group);
},
- deleteRolePermission: function (permission, rolename) {
- this.deletePermission(permission,'roles',rolename);
+ deleteRolePermission: function(permission, rolename) {
+ this.deletePermission(permission, 'roles', rolename);
},
- removeUserFromRole: function (user, role) { //"get,post,put:/mypermission"
+ removeUserFromRole: function(user, role) { //"get,post,put:/mypermission"
var options = {
- method:'DELETE',
- endpoint:'roles/'+role+'/users/'+user
+ method: 'DELETE',
+ endpoint: 'roles/' + role + '/users/' + user
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error removing user from role');
+ $rootScope.$broadcast('alert', 'error',
+ 'error removing user from role');
} else {
$rootScope.$broadcast('role-update-received');
}
});
},
- removeUserFromGroup: function (group, role) { //"get,post,put:/mypermission"
+ removeUserFromGroup: function(group, role) { //"get,post,put:/mypermission"
var options = {
- method:'DELETE',
- endpoint:'roles/'+role+'/groups/'+group
+ method: 'DELETE',
+ endpoint: 'roles/' + role + '/groups/' + group
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- $rootScope.$broadcast('alert', 'error', 'error removing role from the group');
+ $rootScope.$broadcast('alert', 'error',
+ 'error removing role from the group');
} else {
$rootScope.$broadcast('role-update-received');
}
});
},
- createAndroidNotifier: function (name, APIkey) {
+ createAndroidNotifier: function(name, APIkey) {
var options = {
- method:'POST',
- endpoint:'notifiers',
- body:{"apiKey":APIkey,"name":name,"provider":"google"}
+ method: 'POST',
+ endpoint: 'notifiers',
+ body: {
+ "apiKey": APIkey,
+ "name": name,
+ "provider": "google"
+ }
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
console.error(data);
- $rootScope.$broadcast('alert', 'error', 'error creating notifier ');
+ $rootScope.$broadcast('alert', 'error',
+ 'error creating notifier ');
} else {
- $rootScope.$broadcast('alert', 'success', 'New notifier created successfully.');
+ $rootScope.$broadcast('alert', 'success',
+ 'New notifier created successfully.');
$rootScope.$broadcast('notifier-update');
}
});
},
- createAppleNotifier: function (file, name, environment, certificatePassword ) {
+ createAppleNotifier: function(file, name, environment,
+ certificatePassword) {
var provider = 'apple';
var formData = new FormData();
- formData.append("p12Certificate", file);
+ formData.append("p12Certificate", file);
- formData.append('name', name);
- formData.append('provider', provider);
- formData.append('environment', environment);
- formData.append('certificatePassword', certificatePassword || "");
+ formData.append('name', name);
+ formData.append('provider', provider);
+ formData.append('environment', environment);
+ formData.append('certificatePassword', certificatePassword || "");
//var body = {'p12Certificate':file, "name":name,'environment':environment,"provider":provider};
//if(certificatePassword){
- // body.certificatePassword = certificatePassword;
+ // body.certificatePassword = certificatePassword;
//}
var options = {
- method:'POST',
- endpoint:'notifiers',
- formData:formData
+ method: 'POST',
+ endpoint: 'notifiers',
+ formData: formData
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
console.error(data);
- $rootScope.$broadcast('alert', 'error', data.error_description || 'error creating notifier');
+ $rootScope.$broadcast('alert', 'error', data.error_description ||
+ 'error creating notifier');
} else {
- $rootScope.$broadcast('alert', 'success', 'New notifier created successfully.');
+ $rootScope.$broadcast('alert', 'success',
+ 'New notifier created successfully.');
$rootScope.$broadcast('notifier-update');
}
});
},
- deleteNotifier: function (name) {
+ deleteNotifier: function(name) {
var options = {
- method:'DELETE',
- endpoint: 'notifiers/'+name
+ method: 'DELETE',
+ endpoint: 'notifiers/' + name
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'error deleting notifier');
} else {
@@ -769,69 +867,71 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
});
},
- initializeCurrentUser: function (callback) {
- callback = callback || function(){};
- if($rootScope.currentUser && !$rootScope.currentUser.reset){
+ initializeCurrentUser: function(callback) {
+ callback = callback || function() {};
+ if ($rootScope.currentUser && !$rootScope.currentUser.reset) {
callback($rootScope.currentUser);
return $rootScope.$broadcast('current-user-initialized', '');
}
var options = {
- method:'GET',
- endpoint:'management/users/'+ this.client().get('email'),
- mQuery:true
+ method: 'GET',
+ endpoint: 'management/users/' + this.client().get('email'),
+ mQuery: true
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('alert', 'error', 'Error getting user info');
} else {
$rootScope.currentUser = data.data;
- $rootScope.currentUser.profileImg = utility.get_gravatar($rootScope.currentUser.email);
- $rootScope.userEmail =$rootScope.currentUser.email;
+ $rootScope.currentUser.profileImg = utility.get_gravatar(
+ $rootScope.currentUser.email);
+ $rootScope.userEmail = $rootScope.currentUser.email;
callback($rootScope.currentUser);
$rootScope.$broadcast('current-user-initialized', $rootScope.currentUser);
}
});
},
- updateUser: function (user) {
+ updateUser: function(user) {
var body = {};
body.username = user.username;
body.name = user.name;
body.email = user.email;
var options = {
- method:'PUT',
- endpoint:'management/users/' + user.uuid + '/',
- mQuery:true,
- body:body
+ method: 'PUT',
+ endpoint: 'management/users/' + user.uuid + '/',
+ mQuery: true,
+ body: body
};
var self = this;
- this.client().request(options, function (err, data) {
- self.client().set('email',user.email);
- self.client().set('username',user.username);
+ this.client().request(options, function(err, data) {
+ self.client().set('email', user.email);
+ self.client().set('username', user.username);
if (err) {
- return $rootScope.$broadcast('user-update-error',data);
+ return $rootScope.$broadcast('user-update-error', data);
}
$rootScope.currentUser.reset = true;
- self.initializeCurrentUser(function(){
+ self.initializeCurrentUser(function() {
$rootScope.$broadcast('user-update-success', $rootScope.currentUser);
});
});
},
- resetUserPassword: function (user) {
+ resetUserPassword: function(user) {
var body = {};
body.oldpassword = user.oldPassword;
body.newpassword = user.newPassword;
body.username = user.username;
var options = {
- method:'PUT',
- endpoint:'management/users/' + user.uuid + '/',
- body:body,
- mQuery:true
+ method: 'PUT',
+ endpoint: 'management/users/' + user.uuid + '/',
+ body: body,
+ mQuery: true
}
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
- return $rootScope.$broadcast('alert', 'error', 'Error resetting password');
+ return $rootScope.$broadcast('alert', 'error',
+ 'Error resetting password');
}
//remove old and new password fields so they don't end up as part of the entity object
$rootScope.currentUser.oldPassword = '';
@@ -840,67 +940,75 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
});
},
- getOrgCredentials: function () {
+ getOrgCredentials: function() {
var options = {
- method:'GET',
- endpoint:'management/organizations/'+this.client().get('orgName')+'/credentials',
- mQuery:true
+ method: 'GET',
+ endpoint: 'management/organizations/' + this.client().get('orgName') +
+ '/credentials',
+ mQuery: true
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err && data.credentials) {
- $rootScope.$broadcast('alert', 'error', 'Error getting credentials');
+ $rootScope.$broadcast('alert', 'error',
+ 'Error getting credentials');
} else {
$rootScope.$broadcast('org-creds-updated', data.credentials);
}
});
},
- regenerateOrgCredentials: function () {
+ regenerateOrgCredentials: function() {
var self = this;
var options = {
- method:'POST',
- endpoint:'management/organizations/'+ this.client().get('orgName') + '/credentials',
- mQuery:true
+ method: 'POST',
+ endpoint: 'management/organizations/' + this.client().get('orgName') +
+ '/credentials',
+ mQuery: true
};
this.client().request(options, function(err, data) {
if (err && data.credentials) {
- $rootScope.$broadcast('alert', 'error', 'Error regenerating credentials');
+ $rootScope.$broadcast('alert', 'error',
+ 'Error regenerating credentials');
} else {
- $rootScope.$broadcast('alert', 'success', 'Regeneration of credentials complete.');
+ $rootScope.$broadcast('alert', 'success',
+ 'Regeneration of credentials complete.');
$rootScope.$broadcast('org-creds-updated', data.credentials);
}
});
},
- getAppCredentials: function () {
+ getAppCredentials: function() {
var options = {
- method:'GET',
- endpoint:'credentials'
+ method: 'GET',
+ endpoint: 'credentials'
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err && data.credentials) {
- $rootScope.$broadcast('alert', 'error', 'Error getting credentials');
+ $rootScope.$broadcast('alert', 'error',
+ 'Error getting credentials');
} else {
$rootScope.$broadcast('app-creds-updated', data.credentials);
}
});
},
- regenerateAppCredentials: function () {
+ regenerateAppCredentials: function() {
var self = this;
var options = {
- method:'POST',
- endpoint:'credentials'
+ method: 'POST',
+ endpoint: 'credentials'
};
this.client().request(options, function(err, data) {
if (err && data.credentials) {
- $rootScope.$broadcast('alert', 'error', 'Error regenerating credentials');
+ $rootScope.$broadcast('alert', 'error',
+ 'Error regenerating credentials');
} else {
- $rootScope.$broadcast('alert', 'success', 'Regeneration of credentials complete.');
+ $rootScope.$broadcast('alert', 'success',
+ 'Regeneration of credentials complete.');
$rootScope.$broadcast('app-creds-updated', data.credentials);
}
});
},
- signUpUser: function(orgName,userName,name,email,password){
+ signUpUser: function(orgName, userName, name, email, password) {
var formData = {
"organization": orgName,
"username": userName,
@@ -909,138 +1017,160 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
"password": password
};
var options = {
- method:'POST',
- endpoint:'management/organizations',
- body:formData,
- mQuery:true
+ method: 'POST',
+ endpoint: 'management/organizations',
+ body: formData,
+ mQuery: true
};
var client = this.client();
client.request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('register-error', data);
} else {
- $rootScope.$broadcast('register-success',data);
+ $rootScope.$broadcast('register-success', data);
}
});
},
- resendActivationLink: function(id){
+ resendActivationLink: function(id) {
var options = {
method: 'GET',
- endpoint: 'management/users/'+id+'/reactivate',
- mQuery:true
+ endpoint: 'management/users/' + id + '/reactivate',
+ mQuery: true
};
- this.client().request(options, function (err, data) {
+ this.client().request(options, function(err, data) {
if (err) {
$rootScope.$broadcast('resend-activate-error', data);
} else {
- $rootScope.$broadcast('resend-activate-success',data);
+ $rootScope.$broadcast('resend-activate-success', data);
}
});
},
- getAppSettings: function(){
- $rootScope.$broadcast('app-settings-received',{});
+ getAppSettings: function() {
+ $rootScope.$broadcast('app-settings-received', {});
},
- getActivities: function(){
- this.client().request({method:'GET',endpoint:'activities', qs:{limit:200}},function(err,data){
- if(err) return $rootScope.$broadcast('app-activities-error',data);
- var entities = data.entities;
- //set picture if there is none and change gravatar to secure
- entities.forEach(function(entity) {
- if (!entity.actor.picture) {
- entity.actor.picture = window.location.protocol+ "//" + window.location.host + window.location.pathname + "img/user_profile.png"
+ getActivities: function() {
+ this.client().request({
+ method: 'GET',
+ endpoint: 'activities',
+ qs: {
+ limit: 200
+ }
+ }, function(err, data) {
+ if (err) return $rootScope.$broadcast('app-activities-error', data);
+ var entities = data.entities;
+ //set picture if there is none and change gravatar to secure
+ entities.forEach(function(entity) {
+ if (!entity.actor.picture) {
+ entity.actor.picture = window.location.protocol + "//" +
+ window.location.host + window.location.pathname +
+ "img/user_profile.png"
+ } else {
+ entity.actor.picture = entity.actor.picture.replace(
+ /^http:\/\/www.gravatar/i, 'https://secure.gravatar');
+ //note: changing this to use the image on apigee.com - since the gravatar default won't work on any non-public domains such as localhost
+ //this_data.picture = this_data.picture + encodeURI("?d="+window.location.protocol+"//" + window.location.host + window.location.pathname + "images/user_profile.png");
+ if (~entity.actor.picture.indexOf('http')) {
+ entity.actor.picture = entity.actor.picture;
} else {
- entity.actor.picture = entity.actor.picture.replace(/^http:\/\/www.gravatar/i, 'https://secure.gravatar');
- //note: changing this to use the image on apigee.com - since the gravatar default won't work on any non-public domains such as localhost
- //this_data.picture = this_data.picture + encodeURI("?d="+window.location.protocol+"//" + window.location.host + window.location.pathname + "images/user_profile.png");
- if (~entity.actor.picture.indexOf('http')) {
- entity.actor.picture = entity.actor.picture;
- } else {
- entity.actor.picture = 'https://apigee.com/usergrid/img/user_profile.png';
- }
+ entity.actor.picture =
+ 'https://apigee.com/usergrid/img/user_profile.png';
}
+ }
});
- $rootScope.$broadcast('app-activities-received',data.entities);
- });
+ $rootScope.$broadcast('app-activities-received', data.entities);
+ });
},
- getEntityActivities: function(entity, isFeed){
- var route = isFeed ? 'feed' : 'activities'
- var endpoint = entity.get('type') + '/' + entity.get('uuid') + '/'+route ;
- var options = {
- method:'GET',
- endpoint:endpoint,
- qs:{limit:200}
- };
- this.client().request(options, function (err, data) {
- if(err){
- $rootScope.$broadcast(entity.get('type')+'-'+route+'-error',data);
- }
- data.entities.forEach(function(entityInstance) {
- entityInstance.createdDate = (new Date( entityInstance.created)).toUTCString();
- });
- $rootScope.$broadcast(entity.get('type')+'-'+route+'-received',data.entities);
+ getEntityActivities: function(entity, isFeed) {
+ var route = isFeed ? 'feed' : 'activities'
+ var endpoint = entity.get('type') + '/' + entity.get('uuid') + '/' +
+ route;
+ var options = {
+ method: 'GET',
+ endpoint: endpoint,
+ qs: {
+ limit: 200
+ }
+ };
+ this.client().request(options, function(err, data) {
+ if (err) {
+ $rootScope.$broadcast(entity.get('type') + '-' + route + '-error',
+ data);
+ }
+ data.entities.forEach(function(entityInstance) {
+ entityInstance.createdDate = (new Date(entityInstance.created))
+ .toUTCString();
});
+ $rootScope.$broadcast(entity.get('type') + '-' + route +
+ '-received', data.entities);
+ });
},
- addUserActivity:function(user,content){
+ addUserActivity: function(user, content) {
var options = {
"actor": {
- "displayName": user.get('username'),
- "uuid": user.get('uuid'),
- "username":user.get('username')
- },
+ "displayName": user.get('username'),
+ "uuid": user.get('uuid'),
+ "username": user.get('username')
+ },
"verb": "post",
"content": content
};
- this.client().createUserActivity(user.get('username'), options, function(err, activity) { //first argument can be 'me', a uuid, or a username
- if (err) {
- $rootScope.$broadcast('user-activity-add-error', err);
- } else {
- $rootScope.$broadcast('user-activity-add-success', activity);
- }
- });
+ this.client().createUserActivity(user.get('username'), options,
+ function(err, activity) { //first argument can be 'me', a uuid, or a username
+ if (err) {
+ $rootScope.$broadcast('user-activity-add-error', err);
+ } else {
+ $rootScope.$broadcast('user-activity-add-success', activity);
+ }
+ });
},
- runShellQuery:function(method,path,payload){
+ runShellQuery: function(method, path, payload) {
var path = path.replace(/^\//, ''); //remove leading slash if it does
var options = {
"method": method,
- "endpoint":path
+ "endpoint": path
};
- if(payload){
- options["body"]=payload;
+ if (payload) {
+ options["body"] = payload;
}
- this.client().request(options,function(err,data){
- if(err) {
+ this.client().request(options, function(err, data) {
+ if (err) {
$rootScope.$broadcast('shell-error', data);
- }else{
+ } else {
$rootScope.$broadcast('shell-success', data);
}
});
},
- addOrganization:function(user,orgName){
+ addOrganization: function(user, orgName) {
var options = {
- method: 'POST',
- endpoint: 'management/users/'+user.uuid+'/organizations',
- body:{organization:orgName},
- mQuery:true
- }, client = this.client(),self=this;
- client.request(options,function(err,data){
- if(err){
+ method: 'POST',
+ endpoint: 'management/users/' + user.uuid + '/organizations',
+ body: {
+ organization: orgName
+ },
+ mQuery: true
+ },
+ client = this.client(),
+ self = this;
+ client.request(options, function(err, data) {
+ if (err) {
$rootScope.$broadcast('user-add-org-error', data);
- }else{
+ } else {
$rootScope.$broadcast('user-add-org-success', $rootScope.organizations);
}
});
},
- leaveOrganization:function(user,org){
+ leaveOrganization: function(user, org) {
var options = {
method: 'DELETE',
- endpoint: 'management/users/'+user.uuid+'/organizations/'+org.uuid,
- mQuery:true
+ endpoint: 'management/users/' + user.uuid + '/organizations/' + org
+ .uuid,
+ mQuery: true
}
- this.client().request(options,function(err,data){
- if(err){
+ this.client().request(options, function(err, data) {
+ if (err) {
$rootScope.$broadcast('user-leave-org-error', data);
- }else{
- delete $rootScope.organizations[org.name];
+ } else {
+ delete $rootScope.organizations[org.name];
$rootScope.$broadcast('user-leave-org-success', $rootScope.organizations);
}
});
@@ -1051,30 +1181,30 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
* @param {string} url location of the file/endpoint.
* @return {Promise} Resolves to JSON.
*/
- httpGet: function (id, url) {
+ httpGet: function(id, url) {
var items, deferred;
deferred = $q.defer();
$http.get((url || configuration.ITEMS_URL)).
- success(function (data, status, headers, config) {
- var result;
- if (id) {
- angular.forEach(data, function (obj, index) {
- if (obj.id === id) {
- result = obj;
- }
- });
- } else {
- result = data;
- }
- deferred.resolve(result);
- }).
- error(function (data, status, headers, config) {
- $log.error(data, status, headers, config);
- reportError(data,config);
- deferred.reject(data);
- });
+ success(function(data, status, headers, config) {
+ var result;
+ if (id) {
+ angular.forEach(data, function(obj, index) {
+ if (obj.id === id) {
+ result = obj;
+ }
+ });
+ } else {
+ result = data;
+ }
+ deferred.resolve(result);
+ }).
+ error(function(data, status, headers, config) {
+ $log.error(data, status, headers, config);
+ reportError(data, config);
+ deferred.reject(data);
+ });
return deferred.promise;
},
@@ -1085,44 +1215,50 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
* @param {string} successCallback function called on success.
*/
- jsonp: function (objectType,criteriaId,params,successCallback) {
- if(!params){
+ jsonp: function(objectType, criteriaId, params, successCallback) {
+ if (!params) {
params = {};
}
params.demoApp = $rootScope.demoData;
params.access_token = getAccessToken();
params.callback = 'JSON_CALLBACK';
- var uri = $rootScope.urls().DATA_URL + '/' + $rootScope.currentOrg + '/' + $rootScope.currentApp + '/apm/' + objectType + '/' + criteriaId;
- return this.jsonpRaw(objectType,criteriaId,params,uri,successCallback);
+ var uri = $rootScope.urls().DATA_URL + '/' + $rootScope.currentOrg +
+ '/' + $rootScope.currentApp + '/apm/' + objectType + '/' + criteriaId;
+ return this.jsonpRaw(objectType, criteriaId, params, uri,
+ successCallback);
},
- jsonpSimple: function (objectType,appId,params) {
- var uri = $rootScope.urls().DATA_URL + '/' + $rootScope.currentOrg + '/' + $rootScope.currentApp + '/apm/' + objectType + "/" + appId;
- return this.jsonpRaw(objectType,appId,params,uri);
+ jsonpSimple: function(objectType, appId, params) {
+ var uri = $rootScope.urls().DATA_URL + '/' + $rootScope.currentOrg +
+ '/' + $rootScope.currentApp + '/apm/' + objectType + "/" + appId;
+ return this.jsonpRaw(objectType, appId, params, uri);
},
- calculateAverageRequestTimes: function(){
- if(!running){
+ calculateAverageRequestTimes: function() {
+ if (!running) {
var self = this;
running = true;
- setTimeout(function(){
- running=false;
- var length = requestTimes.length < 10 ? requestTimes.length : 10;
- var sum = requestTimes.slice(0, length).reduce(function(a, b) { return a + b });
+ setTimeout(function() {
+ running = false;
+ var length = requestTimes.length < 10 ? requestTimes.length : 10;
+ var sum = requestTimes.slice(0, length).reduce(function(a, b) {
+ return a + b
+ });
var avg = sum / length;
- self.averageRequestTimes = avg/1000;
- if(self.averageRequestTimes > 5){
- $rootScope.$broadcast('request-times-slow',self.averageRequestTimes);
+ self.averageRequestTimes = avg / 1000;
+ if (self.averageRequestTimes > 5) {
+ $rootScope.$broadcast('request-times-slow', self.averageRequestTimes);
}
- },3000);
+ }, 3000);
}
},
- jsonpRaw: function (objectType,appId,params,uri,successCallback) {
- if(typeof successCallback !== 'function'){
+ jsonpRaw: function(objectType, appId, params, uri, successCallback) {
+ if (typeof successCallback !== 'function') {
successCallback = null;
}
- uri = uri || ($rootScope.urls().DATA_URL + '/' + $rootScope.currentOrg + '/' + $rootScope.currentApp + '/' + objectType);
+ uri = uri || ($rootScope.urls().DATA_URL + '/' + $rootScope.currentOrg +
+ '/' + $rootScope.currentApp + '/' + objectType);
- if(!params){
+ if (!params) {
params = {};
}
@@ -1134,91 +1270,102 @@ AppServices.Services.factory('ug', function (configuration, $rootScope,utility,
var deferred = $q.defer();
- var diff = function(){
+ var diff = function() {
currentRequests[uri]--;
- requestTimes.splice(0,0 ,new Date().getTime() - start);
+ requestTimes.splice(0, 0, new Date().getTime() - start);
self.calculateAverageRequestTimes();
};
successCallback && $rootScope.$broadcast("ajax_loading", objectType);
var reqCount = currentRequests[uri] || 0;
- if(self.averageRequestTimes > 5 && reqCount>1){
- setTimeout(function(){
+ if (self.averageRequestTimes > 5 && reqCount > 1) {
+ setTimeout(function() {
deferred.reject(new Error('query in progress'));
- },50);
+ }, 50);
return deferred;
}
currentRequests[uri] = (currentRequests[uri] || 0) + 1;
- $http.jsonp(uri,{params:params}).
- success(function(data, status, headers, config) {
- diff();
- if(successCallback){
- successCallback(data, status, headers, config);
- $rootScope.$broadcast("ajax_finished", objectType);
- }
- deferred.resolve(data);
- }).
- error(function(data, status, headers, config) {
- diff();
- $log.error("ERROR: Could not get jsonp data. " +uri);
- reportError(data,config);
- deferred.reject(data);
- });
+ $http.jsonp(uri, {
+ params: params
+ }).
+ success(function(data, status, headers, config) {
+ diff();
+ if (successCallback) {
+ successCallback(data, status, headers, config);
+ $rootScope.$broadcast("ajax_finished", objectType);
+ }
+ deferred.resolve(data);
+ }).
+ error(function(data, status, headers, config) {
+ diff();
+ $log.error("ERROR: Could not get jsonp data. " + uri);
+ reportError(data, config);
+ deferred.reject(data);
+ });
return deferred.promise;
},
- resource: function(params,isArray) {
+ resource: function(params, isArray) {
//temporary url for REST endpoints
- return $resource($rootScope.urls().DATA_URL + '/:orgname/:appname/:username/:endpoint',
- {
+ return $resource($rootScope.urls().DATA_URL +
+ '/:orgname/:appname/:username/:endpoint', {
- },
- {
+ }, {
get: {
- method:'JSONP',
+ method: 'JSONP',
isArray: isArray,
params: params
},
login: {
- method:'GET',
+ method: 'GET',
url: $rootScope.urls().DATA_URL + '/management/token',
isArray: false,
params: params
},
save: {
- url: $rootScope.urls().DATA_URL + '/' + params.orgname + '/' + params.appname,
- method:'PUT',
+ url: $rootScope.urls().DATA_URL + '/' + params.orgname + '/' +
+ params.appname,
+ method: 'PUT',
isArray: false,
params: params
}
});
},
- httpPost: function(url,callback,payload,headers){
+ httpPost: function(url, callback, payload, headers) {
var accessToken = getAccessToken();
- if(payload){
+ if (payload) {
payload.access_token = accessToken;
- }else{
- payload = {access_token:accessToken}
+ } else {
+ payload = {
+ access_token: accessToken
+ }
}
- if(!headers){
- headers = {Bearer:accessToken};
+ if (!headers) {
+ headers = {
+ Bearer: accessToken
+ };
}
- $http({method: 'POST', url: url, data: payload, headers: headers}).
- success(function(data, status, headers, config) {
- callback(data)
- }).
- error(function(data, status, headers, config) {
- reportError(data,config);
- callback(data)
- });
+ $http({
+ method: 'POST',
+ url: url,
+ data: payload,
+ headers: headers
+ }).
+ success(function(data, status, headers, config) {
+ callback(data)
+ }).
+ error(function(data, status, headers, config) {
+ reportError(data, config);
+ callback(data)
+ });
}
}