Join our webinar on Wednesday, June 26, at 1pm EDTHow Chia Mitigates Risk in the Crypto Industry.Register
Socket
Socket
Sign inDemoInstall

usergrid

Package Overview
Dependencies
6
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.10.3 to 0.10.4

7

changelog.md
##Change log
###0.10.4
- Added new functions for creating, getting, and deleting connections
- Added test cases for said functions
- Fixed change password error
- Added getEntity method to get existing entity from server
###0.10.3

@@ -4,0 +11,0 @@

304

lib/usergrid.js

@@ -1,2 +0,2 @@

/**
/*
* This module is a collection of classes designed to make working with

@@ -34,3 +34,3 @@ * the Appigee App Services API as easy as possible.

//usergrid enpoint
this.URI = 'https://api.usergrid.com';
this.URI = options.URI || 'https://api.usergrid.com';

@@ -58,3 +58,3 @@ //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)

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

@@ -160,2 +160,5 @@ *

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 = {

@@ -171,5 +174,57 @@ client:this,

});
*/
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
var okToSave = (err && 'service_resource_not_found' === data.error) || (!err && getOnExist);
if(okToSave) {
entity.set(options.data); //add the data again just in case
entity.save(function(err, data) {
if (typeof(callback) === 'function') {
callback(err, entity);
}
});
} else {
if (typeof(callback) === 'function') {
callback(err, entity);
}
}
});
}
/*
* 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);
}
});
}
/*
* Main function for creating new collections - should be called directly.

@@ -295,5 +350,5 @@ *

var options = {
method:'GET',
method:'POST',
endpoint:'token',
qs:{
body:{
username: username,

@@ -533,3 +588,3 @@ password: password,

if (item === 'metadata' || item === 'created' || item === 'modified' ||
item === 'type' || item === 'activatted' ) { continue; }
item === 'type' || item === 'activatted' || item ==='uuid') { continue; }
data[item] = entityData[item];

@@ -550,8 +605,10 @@ }

} else {
if (retdata.entities.length) {
var entity = retdata.entities[0];
self.set(entity);
if (retdata.entities) {
if (retdata.entities.length) {
var entity = retdata.entities[0];
self.set(entity);
}
}
//if this is a user, update the password if it has been specified;
var needPasswordChange = (type === 'users' && entityData.oldpassword && entityData.newpassword);
var needPasswordChange = (self.get('type') === 'user' && entityData.oldpassword && entityData.newpassword);
if (needPasswordChange) {

@@ -563,20 +620,18 @@ //Note: we have a ticket in to change PUT calls to /users to accept the password change

pwdata.newpassword = entityData.newpassword;
this._client.request(
{
method:'PUT',
endpoint:type,
body:pwdata
},
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);
}
var options = {
method:'PUT',
endpoint:type+'/password',
body:pwdata
}
self._client.request(options, function (err, data) {
if (err && self._client.logging) {
console.log('could not update user');
}
);
//remove old and new password fields so they don't end up as part of the entity object
self.set('oldpassword', null);
self.set('newpassword', null);
if (typeof(callback) === 'function') {
callback(err, data, self);
}
});
} else if (typeof(callback) === 'function') {

@@ -641,5 +696,7 @@ callback(err, retdata, self);

self.set(data.user);
} else if (data.entities.length) {
var entity = data.entities[0];
self.set(entity);
} else if (data.entities) {
if (data.entities.length) {
var entity = data.entities[0];
self.set(entity);
}
}

@@ -693,5 +750,192 @@ }

/*
* 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;
//connectee info
var connecteeType = entity.get('type');
var connectee = this.getEntityId(entity);
if (!connectee) {
if (typeof(callback) === 'function') {
var error = 'Error trying to delete object - no uuid specified.';
if (self._client.logging) {
console.log(error);
}
callback(true, error);
}
return;
}
//connector info
var connectorType = this.get('type');
var connector = this.getEntityId(this);
if (!connector) {
if (typeof(callback) === 'function') {
var error = 'Error in connect - no uuid specified.';
if (self._client.logging) {
console.log(error);
}
callback(true, error);
}
return;
}
var endpoint = connectorType + '/' + connector + '/' + connection + '/' + connecteeType + '/' + connectee;
var options = {
method:'POST',
endpoint:endpoint
};
this._client.request(options, function (err, data) {
if (err && self._client.logging) {
console.log('entity could not be connected');
}
if (typeof(callback) === 'function') {
callback(err, data);
}
});
}
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;
}
/*
* gets an entities connections
*
* @method getConnections
* @public
* @param {string} connection
* @param {object} entity
* @param {function} callback
* @return {callback} callback(err, data)
*
*/
Usergrid.Entity.prototype.getConnections = function (connection, callback) {
var self = this;
//connector info
var connectorType = this.get('type');
var connector = this.getEntityId(this);
if (!connector) {
if (typeof(callback) === 'function') {
var error = 'Error in getConnections - no uuid specified.';
if (self._client.logging) {
console.log(error);
}
callback(true, error);
}
return;
}
var endpoint = connectorType + '/' + connector + '/' + connection + '/';
var options = {
method:'GET',
endpoint:endpoint
};
this._client.request(options, function (err, data) {
if (err && self._client.logging) {
console.log('entity could not be connected');
}
self[connection] = {};
var length = data.entities.length;
for (var i=0;i<length;i++)
{
if (data.entities[i].type === 'user'){
self[connection][data.entities[i].username] = data.entities[i];
} else {
self[connection][data.entities[i].name] = data.entities[i]
}
}
if (typeof(callback) === 'function') {
callback(err, data);
}
});
}
/*
* disconnects one entity from another
*
* @method disconnect
* @public
* @param {string} connection
* @param {object} entity
* @param {function} callback
* @return {callback} callback(err, data)
*
*/
Usergrid.Entity.prototype.disconnect = function (connection, entity, callback) {
var self = this;
//connectee info
var connecteeType = entity.get('type');
var connectee = this.getEntityId(entity);
if (!connectee) {
if (typeof(callback) === 'function') {
var error = 'Error trying to delete object - no uuid specified.';
if (self._client.logging) {
console.log(error);
}
callback(true, error);
}
return;
}
//connector info
var connectorType = this.get('type');
var connector = this.getEntityId(this);
if (!connector) {
if (typeof(callback) === 'function') {
var error = 'Error in connect - no uuid specified.';
if (self._client.logging) {
console.log(error);
}
callback(true, error);
}
return;
}
var endpoint = connectorType + '/' + connector + '/' + connection + '/' + connecteeType + '/' + connectee;
var options = {
method:'DELETE',
endpoint:endpoint
};
this._client.request(options, function (err, data) {
if (err && self._client.logging) {
console.log('entity could not be disconnected');
}
if (typeof(callback) === 'function') {
callback(err, data);
}
});
}
/*
* The Collection class models Usergrid Collections. It essentially

@@ -698,0 +942,0 @@ * acts as a container for holding Entity objects, while providing

2

package.json
{
"name": "usergrid",
"version": "0.10.3",
"version": "0.10.4",
"description": "A Node.js module for making API calls to App Services (Usergrid) from within Node.js",

@@ -5,0 +5,0 @@ "main": "./lib/usergrid.js",

##Version
Current Version: **0.10.3**
Current Version: **0.10.4**
See change log:
https://github.com/apigee/usergrid-node-module/master/changelog.md
<https://github.com/apigee/usergrid-node-module/blob/master/changelog.md>
##Comments / Questions
Please feel free to send comments or questions:
twitter: @rockerston
email: rod at apigee.com
Or just open github issues. I truly want to know what you think, and will address all suggestions / comments / concerns.
Thank you!
Rod
##Overview

@@ -13,2 +28,8 @@ This Node.js module, which simplifies the process of making API calls to App Services from within Node.js, is provided by [Apigee](http://apigee.com) and is available as an open-source project on github. We welcome your contributions and suggestions. The repository is located here:

You can download this package here:
* Download as a zip file: <https://github.com/apigee/usergrid-node-module/archive/master.zip>
* Download as a tar.gz file: <https://github.com/apigee/usergrid-node-module/archive/master.tar.gz>
To find out more about Apigee App Services, see:

@@ -20,4 +41,5 @@

<http://apigee.com/docs/usergrid/>
<http://apigee.com/docs/app_services>
##Client side Javascript

@@ -30,2 +52,3 @@ Want to make calls to App Services (Usergrid) client-side? No problem - just head over to the Usergrid Javascript SDK:

##Installing

@@ -37,3 +60,2 @@ Use npm:

##Getting started

@@ -72,7 +94,9 @@ Include the module:

##About the samples
All of the samples provided in this readme file come from unit tests in the test.js which is located in the root of this project.
To run this file, first do the following:
To run the test file, first do the following:
1. Change the org-name and app-name to point to your Usergrid account. Log into the [Admin Portal](http://apigee.com/usergrid) to see this information.

@@ -85,84 +109,5 @@ 2. Change the client secret and client id

Read through the samples in this file as they show many examples of how to use this module.
The samples in this file will show you the many ways you can use this module.
##Make some calls
This Usergrid module uses the [request](https://github.com/mikeal/request) module by [mikeal](https://github.com/mikeal). We expose a similar request function and a subset of the options available. This allows you to make basic calls against the API using this format:
client.request(options, callback);
This client.request method uses similar syntax although only the subset of options that is relevant to making calls against the App Services API. For example, to get a list of users:
var options = {
method:'GET',
endpoint:'users'
};
client.request(options, function (err, data) {
if (err) {
error('GET failed');
} else {
//data will contain raw results from API call
success('GET worked');
}
});
Or, to create a new user:
var options = {
method:'POST',
endpoint:'users',
body:{ username:'fred', password:'secret' }
};
client.request(options, function (err, data) {
if (err) {
error('POST failed');
} else {
//data will contain raw results from API call
success('POST worked');
}
});
Or, to update the new user:
var options = {
method:'PUT',
endpoint:'users/fred',
body:{ newkey:'newvalue' }
};
client.request(options, function (err, data) {
if (err) {
error('PUT failed');
} else {
//data will contain raw results from API call
success('PUT worked');
}
});
Or to delete the new user:
var options = {
method:'DELETE',
endpoint:'users/fred'
};
client.request(options, function (err, data) {
if (err) {
error('DELETE failed');
} else {
//data will contain raw results from API call
success('DELETE worked');
}
});
The Options Object for the client.request fuction:
* `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
* `buildCurl` - boolean, set to true if you want to see equivalent curl commands in console.log, defaults to false
You can make any call to the API using the format above. However, in practice using the higher level Entity and Collection objects will make life easier as they take care of much of the heavy lifting.
##Entities and Collections

@@ -183,5 +128,5 @@ Usergrid stores its data as "Entities" in "Collections". Entities are essentially JSON objects and Collections are just like folders for storing these objects. You can learn more about Entities and Collections in the App Services docs:

if (err) {
error('dog not created');
//error - dog not created
} else {
success('dog is created');
//success -dog is created

@@ -202,5 +147,5 @@ //once the dog is created, you can set single properties:

if (err){
error('dog not saved');
//error - dog not saved
} else {
success('new dog is saved');
//success - new dog is saved
}

@@ -219,7 +164,7 @@ });

if (err){
error('dog not refreshed from database');
// error - dog not refreshed from database;
} else {
//dog has been refreshed from the database
//will only work if the UUID for the entity is in the dog object
success('dog entity refreshed from database');
//success - dog entity refreshed from database;
}

@@ -233,5 +178,5 @@ });

if (err){
error('dog not removed from database');
//error - dog not removed from database
} else {
success('dog removed from database'); // no real dogs were harmed!
//success - dog removed from database (no real dogs were harmed!)
dog = null; //no real dogs were harmed!

@@ -241,3 +186,77 @@ }

To set properties on the entity, use the set() method:
//once the dog is created, you can set single properties:
dog.set('breed','Dinosaur');
//or a JSON object:
var data = {
master:'Fred',
state:'hungry'
}
//set is additive, so previously set properties are not overwritten
dog.set(data);
**Note:** These properties are now set locally, but make sure you call the .save() method on the entity to save them back to the database!
To get a single property from the entity, use the get method:
var breed = dog.get('breed');
or
var state = dog.get('state');
or, to get a JSON object with all properties, don't pass a key
var props = dog.get();
Based on the set statements above, our JSON object should look like this:
{
name:'Dino',
type:'dogs',
breed:'Dinosaur',
master:'Fred',
state:'hungry'
}
**Wait!** But what if my entity already exists on the server?
During a client.createEntity call, there are two ways that you can choose to handle this situation. The question is, what should the client do if an entity with the same name, username, or uuid already exists on the server?
1. Give you back an error.
2. Give you back the pre-existing entity.
If you want to get back an error when the entity already exists, then simply call the client.createEntity function as above. If there is a collision, you will get back a 400 However, if you want the existing entity to be returned, then set the getOnExist flag to true:
var options = {
type:'dogs',
name:'Dino',
getOnExist:true
}
client.createEntity(options, function (err, dog) {
if (err) {
//error - dog not created
} else {
//success -dog is created or returned, depending on if it already exists or not
Alternatively, if you know that you only want to retrieve an existing entity, use the getEntity method:
var options = {
type:'users',
username:'marty'
}
client.getEntity(options, function(err, existingUser){
if (err){
//error - existing user not retrieved
} else {
//success - existing user was retrieved
var username = existingUser.get('username');
}
});
##The Collection object

@@ -254,6 +273,6 @@ The Collection object models Collections in the database. Once you start programming your app, you will likely find that this is the most useful method of interacting with the database. Creating a collection will automatically populate the object with entities from the collection. The following example shows how to create a Collection object, then how to use entities once the Collection has been populated with entities from the server:

if (err) {
error('could not make collection');
//error - could not make collection
} else {
success('new Collection worked');
//success - new Collection worked

@@ -268,3 +287,3 @@ //we got the dogs, now display the Entities:

success('looped through dogs');
//success - looped through dogs

@@ -286,5 +305,5 @@ }

if (err) {
error('extra dog not saved or added to collection');
//error - extra dog not saved or added to collection
} else {
success('extra dog saved and added to collection');
//success - extra dog saved and added to collection
}

@@ -311,5 +330,5 @@ });

if (err) {
error('could not get next page of dogs');
//error - could not get next page of dogs
} else {
success('got next page of dogs');
//success - got next page of dogs
//we got the dogs, now display the Entities:

@@ -322,3 +341,3 @@ while(dogs.hasNextEntity()) {

}
success('looped through dogs');
//success - looped through dogs
}

@@ -334,5 +353,5 @@ });

if(err) {
error('could not get previous page of dogs');
//error - could not get previous page of dogs
} else {
success('got next page of dogs');
//success - got next page of dogs
//we got the dogs, now display the Entities:

@@ -345,3 +364,3 @@ while(dogs.hasNextEntity()) {

}
success('looped through dogs');
//success - looped through dogs
}

@@ -361,5 +380,5 @@ });

if (err) {
error('could not get all dogs');
//error - could not get all dogs
} else {
success('got at most 50 dogs');
//success - got at most 50 dogs
}

@@ -424,5 +443,5 @@ }

if (err){
error('user not saved');
//error - user not saved
} else {
success('user saved');
//success - user saved
}

@@ -439,5 +458,5 @@ });

if (err){
error('user not updated');
//error - user not updated
} else {
success('user updated');
//success - user updated
}

@@ -450,5 +469,5 @@ });

if (err){
error('not refreshed');
//error - not refreshed
} else {
success('user refreshed');
//success - user refreshed
}

@@ -461,5 +480,5 @@ });

if (err){
error('user not deleted from database');
//error - user not deleted from database
} else {
success('user deleted from database');
//success - user deleted from database
marty = null; //blow away the local object

@@ -470,2 +489,60 @@ }

###Making connections
Connections are a way to connect to entities with some verb. This is called an entity relationship. For example, if you have a user entity with username of marty, and a dog entity with a name of einstein, then using our RESTful API, you could make a call like this:
POST users/marty/likes/dogs/einstein
This creates a one-way connection between marty and einstein, where marty "likes" einstein.
Complete documentation on the entity relationships API can be found here:
<http://apigee.com/docs/usergrid/content/entity-relationships>
The following code shows you how to create this connection, and then verify that the connection has been made:
marty.connect('likes', dog, function (err, data) {
if (err) {
// error - connection not created
} else {
//call succeeded, so pull the connections back down
marty.getConnections('likes', function (err, data) {
if (err) {
//error - could not get connections
} else {
//verify that connection exists
if (marty.likes.ralphy) {
//success - connection exists
} else {
//error - connection does not exist
}
}
});
}
});
You can also remove connections, by using the disconnect method:
marty.disconnect('likes', dog, function (err, data) {
if (err) {
//error - connection not deleted
} else {
//call succeeded, so pull the connections back down
marty.getConnections('likes', function (err, data) {
if (err) {
//error - error getting connections
} else {
//verify that connection exists
if (marty.likes.einstein) {
//error - connection still exists
} else {
//success - connection deleted
}
}
});
}
});
###To log a user in

@@ -486,5 +563,5 @@ Up to this point, we have shown how you can use the client secret / client id combination to authenticate your calls against the API. For a server-side Node.js app, this may be all you need. However, if you do find that your app requires that you authenticate an individual user, you have several options.

if (err) {
error('could not log user in');
//error - could not log user in
} else {
success('user has been logged in');
//success - user has been logged in

@@ -511,9 +588,8 @@ //the login call will return an OAuth token, which is saved

if(err) {
error('could not get logged in user');
//error - could not get logged in user
} else {
success('got logged in user');
//success - got logged in user
//you can then get info from the user entity object:
var username = user.get('username');
notice('logged in user was: ' + username);

@@ -526,5 +602,5 @@ //to log the user out, call the logout() method

if (client.isLoggedIn()) {
error('logout failed');
//error - logout failed
} else {
success('user has been logged out');
//success - user has been logged out
}

@@ -566,13 +642,103 @@

##Samples / Tests
There is significant coverage of this Usergrid module in the test directory. These files are coded to run under the mocha.
##Making generic calls
If you find that you need to make calls to the API that fall outside of the scope of the Entity and Collection objects, you can use the following format to make any REST calls against the API:
For runnable samples, please see the test.js file in the root of the project. This file covers all the sample code in this readme file and should be run under node:
client.request(options, callback);
$node test.js
This format allows you to make almost any call against the App Services (Usergrid) API. For example, to get a list of users:
var options = {
method:'GET',
endpoint:'users'
};
client.request(options, function (err, data) {
if (err) {
//error - GET failed
} else {
//data will contain raw results from API call
//success - GET worked
}
});
Or, to create a new user:
var options = {
method:'POST',
endpoint:'users',
body:{ username:'fred', password:'secret' }
};
client.request(options, function (err, data) {
if (err) {
//error - POST failed
} else {
//data will contain raw results from API call
//success - POST worked
}
});
Or, to update the new user:
var options = {
method:'PUT',
endpoint:'users/fred',
body:{ newkey:'newvalue' }
};
client.request(options, function (err, data) {
if (err) {
//error - PUT failed
} else {
//data will contain raw results from API call
//success - PUT worked
}
});
Or to delete the new user:
var options = {
method:'DELETE',
endpoint:'users/fred'
};
client.request(options, function (err, data) {
if (err) {
//error - DELETE failed
} else {
//data will contain raw results from API call
//success - DELETE worked
}
});
The Options Object for the client.request fuction:
* `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
* `buildCurl` - boolean, set to true if you want to see equivalent curl commands in console.log, defaults to false
You can make any call to the API using the format above. However, in practice using the higher level Entity and Collection objects will make life easier as they take care of much of the heavy lifting.
###cURL
[cURL](http://curl.haxx.se/) is an excellent way to make calls directly against the API. As mentioned in the **Getting started** section of this guide, one of the parameters you can add to the new client options object is **buildCurl**:
var client = new Usergrid.Client({
orgName:'yourorgname',
appName:'sandbox',
logging: true, //optional - turn on logging, off by default
buildCurl: true //optional - turn on curl commands, off by default
});
If you set this parameter to true, the SDK will build equivalent curl commands and send them to the console.log window. To learn how to see the console log, see this page:
<http://apigee.com/docs/usergrid/content/displaying-app-services-api-calls-curl-commands>
More information on cURL can be found here:
<http://curl.haxx.se/>
## Contributing
We welcome your enhancements!
Like [Usergrid](https://github.com/apigee/usergrid-node-module), the Usergrid Node module is open source and licensed under the Apache License, Version 2.0.
Like [Usergrid](https://github.com/apigee/usergrid-node-module), the Usergrid Javascript SDK is open source and licensed under the Apache License, Version 2.0.

@@ -589,3 +755,3 @@ 1. Fork it

## Copyright
Copyright 2012 Apigee Corporation
Copyright 2013 Apigee Corporation

@@ -592,0 +758,0 @@ Licensed under the Apache License, Version 2.0 (the "License");

@@ -31,6 +31,8 @@ /**

var client = new usergrid.client({
orgName:'yourorgname',
appName:'sandbox',
logging: true, //optional - turn on logging, off by default
//logging: true, //optional - turn on logging, off by default
buildCurl: true //optional - turn on curl commands, off by default
});

@@ -42,91 +44,135 @@

function runner(step, arg){
function runner(step, arg, arg2){
step++;
switch(step)
{
case 1:
notice('-----running step '+step+': GET test');
testGET(step);
break;
case 2:
notice('-----running step '+step+': POST test');
testPOST(step);
break;
case 3:
notice('-----running step '+step+': PUT test');
testPUT(step);
break;
case 4:
notice('-----running step '+step+': DELETE test');
testDELETE(step);
break;
case 5:
notice('-----running step '+step+': prepare database - remove all dogs (no real dogs harmed here!!)');
cleanupAllDogs(step);
break;
case 6:
notice('-----running step '+step+': make a new dog');
makeNewDog(step);
break;
case 7:
notice('-----running step '+step+': update our dog');
updateDog(step, arg);
break;
case 8:
notice('-----running step '+step+': refresh our dog');
refreshDog(step, arg);
break;
case 9:
notice('-----running step '+step+': remove our dog from database (no real dogs harmed here!!)');
removeDogFromDatabase(step, arg);
break;
case 10:
notice('-----running step '+step+': make lots of dogs!');
makeSampleData(step, arg);
break;
case 11:
notice('-----running step '+step+': make a dogs collection and show each dog');
testDogsCollection(step);
break;
case 12:
notice('-----running step '+step+': get the next page of the dogs collection and show each dog');
getNextDogsPage(step, arg);
break;
case 13:
notice('-----running step '+step+': get the previous page of the dogs collection and show each dog');
getPreviousDogsPage(step, arg);
break;
case 14:
notice('-----running step '+step+': remove all dogs from the database (no real dogs harmed here!!)');
cleanupAllDogs(step);
break;
case 15:
notice('-----running step '+step+': prepare database (remove existing user if present)');
prepareDatabaseForNewUser(step);
break;
case 16:
notice('-----running step '+step+': create a new user');
createUser(step);
break;
case 17:
notice('-----running step '+step+': update the user');
updateUser(step, arg);
break;
case 18:
notice('-----running step '+step+': refresh the user from the database');
refreshUser(step, arg);
break;
case 19:
notice('-----running step '+step+': refresh the user from the database');
loginUser(step, arg);
break;
case 20:
notice('-----running step '+step+': remove the user from the database');
destroyUser(step, arg);
break;
default:
notice('-----test complete!-----');
notice('Success count= ' + successCount);
notice('Error count= ' + errorCount);
notice('-----thank you for playing!-----');
case 1:
notice('-----running step '+step+': DELETE user from DB to prep test');
clearUser(step);
break;
case 2:
notice('-----running step '+step+': GET test');
testGET(step);
break;
case 3:
notice('-----running step '+step+': POST test');
testPOST(step);
break;
case 4:
notice('-----running step '+step+': PUT test');
testPUT(step);
break;
case 5:
notice('-----running step '+step+': DELETE test');
testDELETE(step);
break;
case 6:
notice('-----running step '+step+': prepare database - remove all dogs (no real dogs harmed here!!)');
cleanupAllDogs(step);
break;
case 7:
notice('-----running step '+step+': make a new dog');
makeNewDog(step);
break;
case 8:
notice('-----running step '+step+': update our dog');
updateDog(step, arg);
break;
case 9:
notice('-----running step '+step+': refresh our dog');
refreshDog(step, arg);
break;
case 10:
notice('-----running step '+step+': remove our dog from database (no real dogs harmed here!!)');
removeDogFromDatabase(step, arg);
break;
case 11:
notice('-----running step '+step+': make lots of dogs!');
makeSampleData(step, arg);
break;
case 12:
notice('-----running step '+step+': make a dogs collection and show each dog');
testDogsCollection(step);
break;
case 13:
notice('-----running step '+step+': get the next page of the dogs collection and show each dog');
getNextDogsPage(step, arg);
break;
case 14:
notice('-----running step '+step+': get the previous page of the dogs collection and show each dog');
getPreviousDogsPage(step, arg);
break;
case 15:
notice('-----running step '+step+': remove all dogs from the database (no real dogs harmed here!!)');
cleanupAllDogs(step);
break;
case 16:
notice('-----running step '+step+': prepare database (remove existing user if present)');
prepareDatabaseForNewUser(step);
break;
case 17:
notice('-----running step '+step+': create a new user');
createUser(step);
break;
case 18:
notice('-----running step '+step+': update the user');
updateUser(step, arg);
break;
case 19:
notice('-----running step '+step+': get the existing user');
getExistingUser(step, arg);
break;
case 20:
notice('-----running step '+step+': refresh the user from the database');
refreshUser(step, arg);
break;
case 21:
notice('-----running step '+step+': refresh the user from the database');
loginUser(step, arg);
break;
case 22:
notice('-----running step '+step+': refresh the user from the database');
changeUsersPassword(step, arg);
break;
case 23:
notice('-----running step '+step+': refresh the user from the database');
logoutUser(step, arg);
break;
case 24:
notice('-----running step '+step+': refresh the user from the database');
reloginUser(step, arg);
break;
case 25:
notice('-----running step '+step+': logged in user creates dog');
createDog(step, arg);
break;
case 26:
notice('-----running step '+step+': logged in user likes dog');
userLikesDog(step, arg, arg2);
break;
case 27:
notice('-----running step '+step+': logged in user removes likes connection to dog');
removeUserLikesDog(step, arg, arg2);
break;
case 28:
notice('-----running step '+step+': user removes dog');
removeDog(step, arg, arg2);
break;
case 29:
notice('-----running step '+step+': log the user out');
logoutUser(step, arg);
break;
case 30:
notice('-----running step '+step+': remove the user from the database');
destroyUser(step, arg);
break;
case 31:
notice('-----running step '+step+': try to create existing entity');
createExistingEntity(step, arg);
break;
default:
notice('-----test complete!-----');
notice('Success count= ' + successCount);
notice('Error count= ' + errorCount);
notice('-----thank you for playing!-----');
}

@@ -157,2 +203,14 @@ }

//tests
function clearUser(step) {
var options = {
method:'DELETE',
endpoint:'users/fred'
};
client.request(options, function (err, data) {
//data will contain raw results from API call
success('User cleared from DB');
runner(step);
});
}
function testGET(step) {

@@ -511,6 +569,6 @@ var options = {

if (err){
error('user not saved');
error('user not created');
runner(step, marty);
} else {
success('user saved');
success('user created');
runner(step, marty);

@@ -538,2 +596,27 @@ }

function getExistingUser(step, marty) {
var options = {
type:'users',
username:'marty'
}
client.getEntity(options, function(err, existingUser){
if (err){
error('existing user not retrieved');
} else {
success('existing user was retrieved');
var username = existingUser.get('username');
if (username === 'marty'){
success('got existing user username');
} else {
error('could not get existing user username');
}
runner(step, marty);
}
});
}
function refreshUser(step, marty) {

@@ -590,18 +673,3 @@

//to log the user out, call the logout() method
appUserClient.logout();
client.logout();
//verify the logout worked
if (client.isLoggedIn()) {
error('logout failed');
} else {
success('user has been logged out');
}
//since we don't need to App User level calls anymore,
//set the authtype back to client:
client.authType = usergrid.AUTH_CLIENT_ID;
runner(step, marty);
runner(step, user);
}

@@ -615,2 +683,147 @@ });

function changeUsersPassword(step, marty) {
marty.set('oldpassword', 'mysecurepassword');
marty.set('newpassword', 'mynewsecurepassword');
marty.save(function(err){
if (err){
error('user password not updated');
} else {
success('user password updated');
runner(step, marty);
}
});
}
function logoutUser(step, marty) {
//to log the user out, call the logout() method
client.logout();
//verify the logout worked
if (client.isLoggedIn()) {
error('logout failed');
} else {
success('user has been logged out');
}
runner(step, marty);
}
function reloginUser(step, marty) {
username = 'marty';
password = 'mynewsecurepassword';
client.login(username, password,
function (err) {
if (err) {
error('could not relog user in');
} else {
success('user has been re-logged in');
runner(step, marty);
}
}
);
}
//TODO: currently, this code assumes permissions have been set to support user actions. need to add code to show how to add new role and permission programatically
//
//first create a new permission on the default role:
//POST "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions" -d '{"permission":"get,post,put,delete:/dogs/**"}'
//then after user actions, delete the permission on the default role:
//DELETE "https://api.usergrid.com/yourorgname/yourappname/roles/default/permissions?permission=get%2Cpost%2Cput%2Cdelete%3A%2Fdogs%2F**"
function createDog(step, marty) {
//see if marty can create a new dog now that he is logged in
var options = {
type:'dogs',
name:'einstein',
breed:'mutt'
}
client.createEntity(options, function (err, dog) {
if (err) {
error('POST new dog by logged in user failed');
} else {
success('POST new dog by logged in user succeeded');
runner(step, marty, dog);
}
});
}
function userLikesDog(step, marty, dog) {
marty.connect('likes', dog, function (err, data) {
if (err) {
error('connection not created');
runner(step, marty);
} else {
//call succeeded, so pull the connections back down
marty.getConnections('likes', function (err, data) {
if (err) {
error('could not get connections');
} else {
//verify that connection exists
if (marty.likes.einstein) {
success('connection exists');
} else {
error('connection does not exist');
}
runner(step, marty, dog);
}
});
}
});
}
function removeUserLikesDog(step, marty, dog) {
marty.disconnect('likes', dog, function (err, data) {
if (err) {
error('connection not deleted');
runner(step, marty);
} else {
//call succeeded, so pull the connections back down
marty.getConnections('likes', function (err, data) {
if (err) {
error('error getting connections');
} else {
//verify that connection exists
if (marty.likes.einstein) {
error('connection still exists');
} else {
success('connection deleted');
}
runner(step, marty, dog);
}
});
}
});
}
function removeDog(step, marty, dog) {
//now delete the dog from the database
dog.destroy(function(err, data) {
if (err) {
error('dog not removed');
} else {
success('dog removed');
}
});
runner(step, marty);
}
function destroyUser(step, marty) {

@@ -629,1 +842,62 @@

}
function createExistingEntity(step, marty) {
var options = {
type:'dogs',
name:'einstein'
}
client.createEntity(options, function (err, dog) {
if (err) {
error('Create new entity to use for existing entity failed');
} else {
success('Create new entity to use for existing entity succeeded');
var uuid = dog.get('uuid');
//now create new entity, but use same entity name of einstein. This means that
//the original einstein entity now exists. Thus, the new einstein entity should
//be the same as the original + any data differences from the options var:
options = {
type:'dogs',
name:'einstein',
breed:'mutt'
}
client.createEntity(options, function (err, newdog) {
if (err) {
error('Create new entity to use for existing entity failed');
} else {
success('Create new entity to use for existing entity succeeded');
var newuuid = newdog.get('uuid');
if (newuuid === uuid) {
success('UUIDs of new and old entities match');
} else {
error('UUIDs of new and old entities do not match');
}
var breed = newdog.get('breed');
if (breed === 'mutt') {
success('attribute sucesfully set on new entity');
} else {
error('attribute not sucesfully set on new entity');
}
newdog.destroy(function(err){
if (err){
error('existing entity not deleted from database');
} else {
success('existing entity deleted from database');
dog = null; //blow away the local object
newdog = null; //blow away the local object
runner(step);
}
});
}
});
}
});
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc