Refactored UsergridRequest to handle all requests, added additional helpers
diff --git a/helpers/args.js b/helpers/args.js
new file mode 100644
index 0000000..ecef57b
--- /dev/null
+++ b/helpers/args.js
@@ -0,0 +1,7 @@
+'use strict'
+
+var _ = require('lodash')
+
+module.exports = function(args) {
+ return _.flattenDeep(Array.prototype.slice.call(args))
+}
\ No newline at end of file
diff --git a/helpers/build.js b/helpers/build.js
index c23e81d..8d46952 100644
--- a/helpers/build.js
+++ b/helpers/build.js
@@ -12,12 +12,12 @@
_ = require('lodash')
module.exports = {
- url: function(client, options) {
+ uri: function(client, options) {
return urljoin(
client.baseUrl,
client.orgId,
client.appId,
- options.type,
+ options.path || options.type,
_.isString(options.uuidOrName) ? options.uuidOrName : ""
)
},
@@ -84,7 +84,8 @@
var options = {
client: client,
- method: 'GET'
+ method: 'GET',
+ callback: helpers.cb(args)
}
// if a preformatted options argument passed, assign it to options
@@ -92,8 +93,6 @@
_.assign(options, args[0])
}
- options.callback = helpers.cb(_.last(args.filter(_.isFunction)))
-
options.type = _.first([options.type, ok(args).getIfExists('0._type'), args[0]].filter(_.isString))
options.query = _.first([options.query, args[0]].filter(function(property) {
@@ -131,7 +130,8 @@
var options = {
client: client,
- method: 'PUT'
+ method: 'PUT',
+ callback: helpers.cb(args)
}
// if a preformatted options argument passed, assign it to options
@@ -139,8 +139,6 @@
_.assign(options, args[0])
}
- options.callback = helpers.cb(_.last(args.filter(_.isFunction)))
-
options.body = _.first([options.entity, options.body, args[2], args[1], args[0]].filter(function(property) {
return _.isObject(property) && !_.isFunction(property) && !(property instanceof UsergridQuery)
}))
@@ -179,7 +177,8 @@
var options = {
client: client,
- method: 'POST'
+ method: 'POST',
+ callback: helpers.cb(args)
}
// if a preformatted options argument passed, assign it to options
@@ -187,8 +186,6 @@
_.assign(options, args[0])
}
- options.callback = helpers.cb(_.last(args.filter(_.isFunction)))
-
options.body = _.first([options.entities, options.entity, options.body, args[1], args[0]].filter(function(property) {
return _.isArray(property) && _.isObject(property[0]) && !_.isFunction(property[0]) || _.isObject(property) && !_.isFunction(property)
}))
@@ -219,7 +216,8 @@
var options = {
client: client,
- method: 'DELETE'
+ method: 'DELETE',
+ callback: helpers.cb(args)
}
// if a preformatted options argument passed, assign it to options
@@ -227,7 +225,6 @@
_.assign(options, args[0])
}
- options.callback = helpers.cb(_.last(args.filter(_.isFunction)))
options.type = _.first([options.type, ok(options).getIfExists('entity.type'), args[0]._type, args[0]].filter(_.isString))
options.entity = _.first([options.entity, args[0]].filter(function(property) {
return (property instanceof UsergridEntity)
@@ -245,7 +242,7 @@
return options
},
- connection: function(client, args) {
+ connection: function(client, method, args) {
/* connect supports the following constructor patterns:
@@ -277,9 +274,11 @@
*/
var options = {
+ client: client,
+ method: method,
entity: {},
to: {},
- callback: helpers.cb(_.last(args.filter(_.isFunction)))
+ callback: helpers.cb(args)
}
// if a preformatted options argument passed, assign it to options
@@ -367,7 +366,9 @@
*/
var options = {
- callback: helpers.cb(_.last(args.filter(_.isFunction)))
+ client: client,
+ method: 'GET',
+ callback: helpers.cb(args)
}
// if a preformatted options argument passed, assign it to options
diff --git a/helpers/cb.js b/helpers/cb.js
index 21ed2f7..8c62591 100644
--- a/helpers/cb.js
+++ b/helpers/cb.js
@@ -1,7 +1,10 @@
'use strict'
-var _ = require('lodash')
+var ok = require('objectkit'),
+ _ = require('lodash')
-module.exports = function(callback) {
- return _.isFunction(callback) ? callback : function() {}
+module.exports = function() {
+ var args = _.flattenDeep(Array.prototype.slice.call(arguments))
+ var emptyFunc = function() {}
+ return _.first(_.flattenDeep([args.reverse(), ok(args).getIfExists('0.callback'), emptyFunc]).filter(_.isFunction))
}
\ No newline at end of file
diff --git a/helpers/client.js b/helpers/client.js
index d91849e..94da11e 100644
--- a/helpers/client.js
+++ b/helpers/client.js
@@ -12,7 +12,7 @@
} else if (Usergrid.isInitialized) {
client = Usergrid
} else {
- throw new Error("This method requires a valid UsergridClient instance (or the Usergrid shared instance) to be initialized")
+ throw new Error("This method requires a valid UsergridClient instance as an argument (or the Usergrid shared instance to be initialized)")
}
return client
}
diff --git a/helpers/index.js b/helpers/index.js
index cc4f20e..954e353 100644
--- a/helpers/index.js
+++ b/helpers/index.js
@@ -1,22 +1,26 @@
'use strict'
-var client = require('./client'),
+var args = require('./args'),
+ client = require('./client'),
cb = require('./cb'),
build = require('./build'),
query = require('./query'),
config = require('./config'),
time = require('./time'),
mutability = require('./mutability'),
+ user = require('./user'),
_ = require('lodash')
// by mixing this in here, lodash-uuid is available everywhere lodash is used.
_.mixin(require('lodash-uuid'))
module.exports = _.assign(module.exports, {
+ args: args,
client: client,
cb: cb,
build: build,
query: query,
config: config,
- time: time
+ time: time,
+ user: user
}, mutability)
\ No newline at end of file
diff --git a/helpers/user.js b/helpers/user.js
new file mode 100644
index 0000000..470cf06
--- /dev/null
+++ b/helpers/user.js
@@ -0,0 +1,9 @@
+'use strict'
+
+var _ = require('lodash')
+
+module.exports = {
+ uniqueId: function(user) {
+ return _.first([user.uuid, user.username, user.email].filter(_.isString))
+ }
+}
\ No newline at end of file
diff --git a/lib/appAuth.js b/lib/appAuth.js
index 493415d..157db3e 100644
--- a/lib/appAuth.js
+++ b/lib/appAuth.js
@@ -1,12 +1,13 @@
'use strict'
var UsergridAuth = require('./auth'),
+ helpers = require('../helpers'),
util = require('util'),
_ = require('lodash')
var UsergridAppAuth = function(options) {
var self = this
- var args = _.flatten(Array.prototype.slice.call(arguments), true)
+ var args = _.flattenDeep(helpers.args(arguments))
if (_.isPlainObject(args[0])) {
options = args[0]
}
diff --git a/lib/auth.js b/lib/auth.js
index 3a20da3..7d8eefa 100644
--- a/lib/auth.js
+++ b/lib/auth.js
@@ -1,10 +1,12 @@
'use strict'
-var UsergridAuth = function() {
+var UsergridAuth = function(token, expiry) {
var self = this
- self.token = undefined
- self.expiry = 0
+ self.token = token || undefined
+ self.expiry = expiry || 0
+
+ var usingToken = (token) ? true : false
Object.defineProperty(self, "hasToken", {
get: function() {
@@ -15,7 +17,7 @@
Object.defineProperty(self, "isExpired", {
get: function() {
- return (Date.now() >= self.expiry)
+ return usingToken || (Date.now() >= self.expiry)
},
configurable: true
})
diff --git a/lib/client.js b/lib/client.js
index d8c8843..898478c 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -1,8 +1,7 @@
'use strict'
-var UsergridRequest = require('./request'),
- request = require('request'),
- helpers = require('../helpers'),
+var helpers = require('../helpers'),
+ UsergridRequest = require('./request'),
UsergridResponse = require('./response'),
UsergridResponseError = require('./responseError'),
UsergridAuth = require('./auth'),
@@ -54,64 +53,32 @@
UsergridClient.prototype = {
GET: function() {
- return new UsergridRequest(helpers.build.GET(this, Array.prototype.slice.call(arguments)))
+ return new UsergridRequest(helpers.build.GET(this, helpers.args(arguments)))
},
PUT: function() {
- return new UsergridRequest(helpers.build.PUT(this, Array.prototype.slice.call(arguments)))
+ return new UsergridRequest(helpers.build.PUT(this, helpers.args(arguments)))
},
POST: function() {
- return new UsergridRequest(helpers.build.POST(this, Array.prototype.slice.call(arguments)))
+ return new UsergridRequest(helpers.build.POST(this, helpers.args(arguments)))
},
DELETE: function() {
- return new UsergridRequest(helpers.build.DELETE(this, Array.prototype.slice.call(arguments)))
+ return new UsergridRequest(helpers.build.DELETE(this, helpers.args(arguments)))
},
connect: function() {
- var Usergrid = require('../usergrid')
- if (this === Usergrid && !Usergrid.isInitialized) {
- throw new Error('The Usergrid shared instance has not been initialized')
- }
- var options = helpers.build.connection(this, Array.prototype.slice.call(arguments))
- request({
- uri: options.uri,
- headers: helpers.build.headers(this),
- method: 'POST',
- json: true
- }, function(error, response) {
- var usergridResponse = new UsergridResponse(response)
- options.callback(error || usergridResponse.error, usergridResponse, usergridResponse.entities)
- })
+ return new UsergridRequest(helpers.build.connection(this, 'POST', helpers.args(arguments)))
},
disconnect: function() {
- var options = helpers.build.connection(this, Array.prototype.slice.call(arguments))
- request({
- uri: options.uri,
- headers: helpers.build.headers(this),
- method: 'DELETE',
- json: true
- }, function(error, response) {
- var usergridResponse = new UsergridResponse(response)
- options.callback(error || usergridResponse.error, usergridResponse, usergridResponse.entities)
- })
+ return new UsergridRequest(helpers.build.connection(this, 'DELETE', helpers.args(arguments)))
},
- getConnections: function() {
- var options = helpers.build.getConnections(this, Array.prototype.slice.call(arguments))
- request({
- uri: options.uri,
- headers: helpers.build.headers(this),
- method: 'GET',
- json: true
- }, function(error, response) {
- var usergridResponse = new UsergridResponse(response)
- options.callback(error || usergridResponse.error, usergridResponse, usergridResponse.entities)
- })
+ getConnections: function() {
+ return new UsergridRequest(helpers.build.getConnections(this, helpers.args(arguments)))
},
setAppAuth: function(options) {
- this.appAuth = (typeof options === 'string') ? Array.prototype.slice.call(arguments) : options
+ this.appAuth = (typeof options === 'string') ? helpers.args(arguments) : options
},
- authenticateApp: function(options, callback) {
+ authenticateApp: function(options) {
var self = this
- callback = helpers.cb(callback || options)
-
+ var callback = helpers.cb(helpers.args(arguments))
var auth = (options instanceof UsergridAppAuth) ? options : self.appAuth || new UsergridAppAuth(options)
if (!(auth instanceof UsergridAppAuth)) {
@@ -120,39 +87,36 @@
throw new Error('authenticateApp() failed because clientId or clientSecret are missing')
}
- auth.type = 'token'
-
- request({
- uri: helpers.build.url(self, auth),
- headers: helpers.build.headers(self),
- body: helpers.build.appLoginBody(auth),
+ var options = {
+ client: self,
+ path: 'token',
method: 'POST',
- json: true
- }, function(error, response, body) {
- if (response.statusCode === 200) {
+ body: helpers.build.appLoginBody(auth)
+ }
+
+ return new UsergridRequest(options, function(error, usergridResponse, body) {
+ if (usergridResponse.ok) {
if (!self.appAuth) {
self.appAuth = auth
}
self.appAuth.token = body.access_token
self.appAuth.expiry = helpers.time.expiry(body.expires_in)
self.appAuth.tokenTtl = body.expires_in
- } else {
- error = new UsergridResponseError(response.body)
}
- callback(error, response, body.access_token)
+ callback(error, usergridResponse, body.access_token)
})
},
- authenticateUser: function(options, callback) {
+ authenticateUser: function(options) {
var self = this
- callback = helpers.cb(callback || options)
+ var callback = helpers.cb(helpers.args(arguments))
var UsergridUser = require('./user')
var currentUser = new UsergridUser(options)
- currentUser.login(self, function(error, response, token) {
- if (response.statusCode === 200) {
+ currentUser.login(self, function(error, usergridResponse, token) {
+ if (usergridResponse.ok) {
self.currentUser = currentUser
}
- callback(error, response, token)
+ callback(error, usergridResponse, token)
})
}
}
diff --git a/lib/entity.js b/lib/entity.js
index 20c4669..3983f84 100644
--- a/lib/entity.js
+++ b/lib/entity.js
@@ -8,7 +8,7 @@
var UsergridEntity = function() {
var self = this
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
if (!args[0]) {
throw new Error('A UsergridEntity object was initialized using an empty argument')
@@ -81,9 +81,9 @@
}
},
reload: function() {
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
+ var callback = helpers.cb(args)
client.GET(this, function(err, usergridResponse) {
helpers.setWritable(this, ['uuid', 'name', 'type', 'created'])
_.assign(this, usergridResponse.entity)
@@ -92,9 +92,9 @@
}.bind(this))
},
save: function() {
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
+ var callback = helpers.cb(args)
client.PUT(this, function(err, usergridResponse) {
helpers.setWritable(this, ['uuid', 'name', 'type', 'created'])
_.assign(this, usergridResponse.entity)
@@ -103,9 +103,9 @@
}.bind(this))
},
remove: function() {
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
+ var callback = helpers.cb(args)
client.DELETE(this, function(err, usergridResponse) {
callback(err || usergridResponse.error, usergridResponse, this)
}.bind(this))
@@ -114,19 +114,19 @@
uploadAsset: function() {},
downloadAsset: function() {},
connect: function() {
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
args.unshift(this)
return client.connect.apply(client, args)
},
disconnect: function() {
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
args.unshift(this)
return client.disconnect.apply(client, args)
},
getConnections: function() {
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
args.splice(1, 0, this)
return client.getConnections.apply(client, args)
diff --git a/lib/request.js b/lib/request.js
index bfda17c..a387a5c 100644
--- a/lib/request.js
+++ b/lib/request.js
@@ -9,12 +9,21 @@
_ = require('lodash')
var UsergridRequest = function(options) {
- if (!_.isString(options.type)) {
- throw new Error('"type" (collection name) parameter is required when making a request')
+
+ var client = helpers.client.validate(options.client)
+ var callback = helpers.cb(helpers.args(arguments))
+
+ if (!_.isString(options.type) && !_.isString(options.path) && !_.isString(options.uri)) {
+ throw new Error('one of "type" (collection name), "path", or "uri" parameters are required when initializing a UsergridRequest')
+ }
+ if (!_.includes(['GET', 'PUT', 'POST', 'DELETE'], options.method)) {
+ throw new Error('"method" parameter is required when initializing a UsergridRequest')
}
- request(helpers.build.url(options.client, options), {
- headers: helpers.build.headers(options.client),
+ var uri = options.uri || helpers.build.uri(client, options)
+
+ request(uri, {
+ headers: helpers.build.headers(client),
body: options.body,
json: true,
method: options.method,
@@ -22,10 +31,10 @@
ql: options.query._ql || undefined,
limit: options.query._limit,
cursor: options.query._cursor
- } : undefined
+ } : options.qs
}, function(error, response) {
var usergridResponse = new UsergridResponse(response)
- options.callback(error || usergridResponse.error, usergridResponse, usergridResponse.entities)
+ callback(error || usergridResponse.error, usergridResponse, usergridResponse.entities || usergridResponse.body)
})
}
diff --git a/lib/response.js b/lib/response.js
index 6cc6997..63a4b20 100644
--- a/lib/response.js
+++ b/lib/response.js
@@ -8,40 +8,46 @@
var UsergridResponse = function(response) {
var self = this
+ self.ok = false
if (!response) {
return
- } else if (ok(response.body).has('entities') && response.statusCode < 400) {
+ } else if (response.statusCode < 400) {
+ self.ok = true
var UsergridEntity = require('./entity.js'),
UsergridUser = require('./user.js')
+
+ _.assign(self, response)
- var entities = response.body.entities.map(function(en) {
- var entity = new UsergridEntity(en)
- if (entity.isUser) {
- entity = new UsergridUser(entity)
+ if (ok(response.body).has('entities')) {
+ var entities = response.body.entities.map(function(en) {
+ var entity = new UsergridEntity(en)
+ if (entity.isUser) {
+ entity = new UsergridUser(entity)
+ }
+ return entity
+ })
+
+ _.assign(self, {
+ metadata: _.cloneDeep(response.body),
+ entities: entities
+ })
+ delete self.metadata.entities
+ self.first = _.first(entities) || undefined
+ self.entity = self.first
+ self.last = _.last(entities) || undefined
+ if (ok(self).getIfExists('metadata.path') === '/users') {
+ self.user = self.first
+ self.users = self.entities
}
- return entity
- })
- _.assign(self, response, {
- metadata: _.cloneDeep(response.body),
- entities: entities
- })
- delete self.metadata.entities
- self.first = _.first(entities) || undefined
- self.entity = self.first
- self.last = _.last(entities) || undefined
- if (ok(self).getIfExists('metadata.path') === '/users') {
- self.user = self.first
- self.users = self.entities
+ Object.defineProperty(self, 'hasNextPage', {
+ get: function() {
+ return ok(self).has('metadata.cursor')
+ }
+ })
+
+ helpers.setReadOnly(self.metadata)
}
-
- Object.defineProperty(self, 'hasNextPage', {
- get: function() {
- return ok(self).has('metadata.cursor')
- }
- })
-
- helpers.setReadOnly(self.metadata)
} else {
_.assign(self, response, {
error: new UsergridResponseError(response.body)
@@ -52,8 +58,8 @@
UsergridResponse.prototype = {
loadNextPage: function() {
- var args = Array.prototype.slice.call(arguments)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
+ var args = helpers.args(arguments)
+ var callback = helpers.cb(args)
if (!this.metadata.cursor) {
callback()
}
diff --git a/lib/user.js b/lib/user.js
index 82ea568..81bcb6e 100644
--- a/lib/user.js
+++ b/lib/user.js
@@ -3,8 +3,8 @@
var UsergridEntity = require('./entity'),
UsergridQuery = require('./query'),
UsergridUserAuth = require('./userAuth'),
+ UsergridRequest = require('./request'),
UsergridResponseError = require('./responseError'),
- request = require('request'),
helpers = require('../helpers'),
ok = require('objectkit'),
util = require('util'),
@@ -28,9 +28,9 @@
var CheckAvailable = function() {
var self = this
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
+ var callback = helpers.cb(args)
var checkQuery
if (args[0].username && args[0].email) {
@@ -51,76 +51,71 @@
UsergridUser.prototype = {
create: function() {
var self = this
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
- client.POST(self, function(err, usergridResponse) {
+ var callback = helpers.cb(args)
+ client.POST(self, function(error, usergridResponse) {
delete self.password
- _.assign(self, usergridResponse.entity)
- callback(err || usergridResponse.error, usergridResponse, usergridResponse.user)
+ _.assign(self, usergridResponse.user)
+ callback(error, usergridResponse, usergridResponse.user)
}.bind(self))
},
login: function() {
var self = this
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
var client = helpers.client.validate(args)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
- client.POST('token', helpers.build.userLoginBody(self), function(error, response) {
+ var callback = helpers.cb(args)
+ return new UsergridRequest({
+ client: self,
+ path: 'token',
+ method: 'POST',
+ body: helpers.build.userLoginBody(self)
+ }, function(error, usergridResponse, body) {
delete self.password
- if (response.statusCode === 200) {
- self.auth = new UsergridUserAuth(response.body.user)
- self.auth.token = response.body.access_token
- self.auth.expiry = helpers.time.expiry(response.body.expires_in)
- self.auth.tokenTtl = response.body.expires_in
- } else {
- error = new UsergridResponseError(response.body)
+ if (usergridResponse.ok) {
+ self.auth = new UsergridUserAuth(body.user)
+ self.auth.token = body.access_token
+ self.auth.expiry = helpers.time.expiry(body.expires_in)
+ self.auth.tokenTtl = body.expires_in
}
- callback(error || response.error, response, response.body.access_token)
- }.bind(self))
+ callback(usergridResponse.error, usergridResponse, body.access_token)
+ })
},
logout: function() {
var self = this
- var args = _.flatten(Array.prototype.slice.call(arguments), true)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
+ var args = helpers.args(arguments)
+ var callback = helpers.cb(args)
if (!self.auth || !self.auth.isValid) {
return callback({
name: 'no_valid_token',
description: 'this user does not have a valid token'
})
}
+
var client = helpers.client.validate(args)
var revokeAll = _.first(args.filter(_.isBoolean)) || false
- var userId = _.first([self.uuid, self.username, self.email].filter(_.isString))
- var url = util.format("%s%s/revoketoken%s", helpers.build.url(client, {
- type: 'user'
- }), userId, (revokeAll) ? "s" : "")
- request(url, {
- headers: helpers.build.headers(client),
- json: true,
+
+ return new UsergridRequest({
+ client: self,
+ path: util.format("users/%s/revoketoken%s", helpers.user.uniqueId(self), (revokeAll) ? "s" : ""),
method: 'PUT',
qs: (!revokeAll) ? {
token: self.auth.token
} : undefined
- }, function(error, response) {
- var UsergridResponse = require('./response'),
- usergridResponse = new UsergridResponse(response)
- if (usergridResponse.statusCode === 200) {
- self.auth.destroy()
- } else {
- error = new UsergridResponseError(response.body)
- }
- callback(error || usergridResponse.error, usergridResponse, (usergridResponse.statusCode === 200))
+ }, function(error, usergridResponse, body) {
+ self.auth.destroy()
+ callback(error, usergridResponse, usergridResponse.ok)
})
},
logoutAllSessions: function() {
- var args = Array.prototype.slice.call(arguments)
+ var args = helpers.args(arguments)
args.unshift(true)
return this.logout.apply(this, args)
},
resetPassword: function() {
var self = this
- var args = _.flatten(Array.prototype.slice.call(arguments), true)
- var callback = helpers.cb(_.last(args.filter(_.isFunction)))
+ var args = helpers.args(arguments)
+ var callback = helpers.cb(args)
var client = helpers.client.validate(args)
var body = {
oldpassword: _.isPlainObject(args[0]) ? args[0].oldPassword : _.isString(args[0]) ? args[0] : undefined,
@@ -129,22 +124,13 @@
if (!body.oldpassword || !body.newpassword) {
throw new Error('"oldPassword" and "newPassword" properties are required when resetting a user password')
}
- var userId = _.first([self.uuid, self.username, self.email].filter(_.isString))
- var url = util.format("%s%s/password", helpers.build.url(client, {
- type: 'user'
- }), userId)
- request(url, {
- headers: helpers.build.headers(client),
- json: true,
+ return new UsergridRequest({
+ client: self,
+ path: util.format('users/%s/password', helpers.user.uniqueId(self)),
method: 'PUT',
body: body
- }, function(error, response) {
- var UsergridResponse = require('./response'),
- usergridResponse = new UsergridResponse(response)
- if (usergridResponse.statusCode >= 400) {
- error = new UsergridResponseError(response.body)
- }
- callback(error || usergridResponse.error, usergridResponse, (usergridResponse.statusCode < 400))
+ }, function(error, usergridResponse, body) {
+ callback(error, usergridResponse, usergridResponse.ok)
})
}
}
diff --git a/lib/userAuth.js b/lib/userAuth.js
index 33cde69..e6fa8ff 100644
--- a/lib/userAuth.js
+++ b/lib/userAuth.js
@@ -1,12 +1,13 @@
'use strict'
var UsergridAuth = require('./auth'),
+ helpers = require('../helpers'),
util = require('util'),
_ = require('lodash')
var UsergridUserAuth = function(options) {
var self = this
- var args = _.flatten(Array.prototype.slice.call(arguments), true)
+ var args = _.flattenDeep(helpers.args(arguments))
if (_.isPlainObject(args[0])) {
options = args[0]
}
diff --git a/tests/lib/client.auth.test.js b/tests/lib/client.auth.test.js
index 41c0d92..a247948 100644
--- a/tests/lib/client.auth.test.js
+++ b/tests/lib/client.auth.test.js
@@ -13,8 +13,6 @@
UsergridUserAuth = require('../../lib/userAuth'),
_ = require('lodash')
-_.mixin(require('lodash-uuid'))
-
var _uuid,
_slow = 500,
_timeout = 4000
@@ -34,8 +32,8 @@
})
})
- it('should return a 200 ok', function() {
- response.statusCode.should.equal(200)
+ it('response.ok should be true', function() {
+ response.ok.should.be.true()
})
it('should have a valid token', function() {
@@ -154,8 +152,8 @@
}).throw()
})
- it('should return a 200 ok', function() {
- response.statusCode.should.equal(200)
+ it('response.ok should be true', function() {
+ response.ok.should.be.true()
})
it('should have a valid token', function() {
@@ -190,7 +188,7 @@
var ttlInMilliseconds = 500000
var userAuth = new UsergridUserAuth(config.test.username, config.test.password, ttlInMilliseconds)
client.authenticateUser(userAuth, function(err, response, token) {
- response.statusCode.should.equal(200)
+ response.ok.should.be.true()
client.currentUser.auth.token.should.equal(token)
response.body.expires_in.should.equal(ttlInMilliseconds / 1000)
done()
diff --git a/tests/lib/client.connections.test.js b/tests/lib/client.connections.test.js
index 6f4c9a9..1a1d7ec 100644
--- a/tests/lib/client.connections.test.js
+++ b/tests/lib/client.connections.test.js
@@ -47,7 +47,7 @@
var relationship = "foos"
client.connect(entity1, relationship, entity2, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[relationship].should.equal(urljoin(
"/",
@@ -67,7 +67,7 @@
var relationship = "bars"
client.connect(entity1, relationship, entity2.uuid, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[relationship].should.equal(urljoin(
"/",
@@ -87,7 +87,7 @@
var relationship = "bazzes"
client.connect(entity1.type, entity1.uuid, relationship, entity2.uuid, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[relationship].should.equal(urljoin(
"/",
@@ -107,7 +107,7 @@
var relationship = "quxes"
client.connect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[relationship].should.equal(urljoin(
"/",
@@ -131,7 +131,7 @@
}
client.connect(options, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, options.relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[options.relationship].should.equal(urljoin(
"/",
@@ -233,7 +233,7 @@
var relationship = "foos"
client.disconnect(entity1, relationship, entity2, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.entities.should.be.an.Array().with.lengthOf(0)
done()
@@ -248,7 +248,7 @@
var relationship = "bars"
client.disconnect(entity1.type, entity1.uuid, relationship, entity2.uuid, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.entities.should.be.an.Array().with.lengthOf(0)
done()
@@ -263,7 +263,7 @@
var relationship = "bazzes"
client.disconnect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.entities.should.be.an.Array().with.lengthOf(0)
done()
@@ -282,7 +282,7 @@
}
client.disconnect(options, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, options.relationship, function(err, usergridResponse) {
usergridResponse.entities.should.be.an.Array().with.lengthOf(0)
done()
diff --git a/tests/lib/client.init.test.js b/tests/lib/client.init.test.js
index 407132b..827863f 100644
--- a/tests/lib/client.init.test.js
+++ b/tests/lib/client.init.test.js
@@ -10,8 +10,6 @@
UsergridAppAuth = require('../../lib/appAuth'),
_ = require('lodash')
-_.mixin(require('lodash-uuid'))
-
describe('initialization', function() {
it('should fail to initialize without an orgId and appId', function() {
should(function() {
diff --git a/tests/lib/client.rest.test.js b/tests/lib/client.rest.test.js
index ead846a..c3a1e3b 100644
--- a/tests/lib/client.rest.test.js
+++ b/tests/lib/client.rest.test.js
@@ -10,8 +10,6 @@
UsergridAppAuth = require('../../lib/appAuth'),
_ = require('lodash')
-_.mixin(require('lodash-uuid'))
-
var _uuid,
_slow = 500,
_timeout = 4000
@@ -34,8 +32,8 @@
client.GET(config.test.collection)
})
- it('should return a 200 ok', function() {
- response.statusCode.should.equal(200)
+ it('response.ok should be true', function() {
+ response.ok.should.be.true()
})
it('response.entities should be an array', function() {
@@ -93,8 +91,8 @@
client.POST(config.test.collection, {})
})
- it('should return a 200 ok', function() {
- response.statusCode.should.equal(200)
+ it('response.ok should be true', function() {
+ response.ok.should.be.true()
})
it('response.entities should be an array', function() {
@@ -223,8 +221,8 @@
client.PUT(config.test.collection, _uuid, {})
})
- it('should return a 200 ok', function() {
- response.statusCode.should.equal(200)
+ it('response.ok should be true', function() {
+ response.ok.should.be.true()
})
it('response.entities should be an array with a single entity', function() {
diff --git a/tests/lib/client.test.js b/tests/lib/client.test.js
new file mode 100644
index 0000000..a6bc370
--- /dev/null
+++ b/tests/lib/client.test.js
@@ -0,0 +1,184 @@
+'use strict'
+
+var should = require('should'),
+ urljoin = require('url-join'),
+ config = require('../../helpers').config,
+ UsergridClient = require('../../lib/client'),
+ UsergridEntity = require('../../lib/entity'),
+ UsergridQuery = require('../../lib/query'),
+ UsergridAuth = require('../../lib/auth'),
+ UsergridAppAuth = require('../../lib/appAuth'),
+ _ = require('lodash')
+
+var _uuid,
+ _slow = 500,
+ _timeout = 4000
+
+describe('authenticateApp()', function() {
+
+ this.slow(_slow)
+ this.timeout(_timeout)
+
+ var response, token, client = new UsergridClient()
+ before(function(done) {
+ client.setAppAuth(config.clientId, config.clientSecret)
+ client.authenticateApp(function(err, r, t) {
+ response = r
+ token = t
+ done()
+ })
+ })
+
+ it('should fail when called without a clientId and clientSecret', function() {
+ should(function() {
+ var client = new UsergridClient()
+ client.setAppAuth(undefined, undefined, 0)
+ client.authenticateApp()
+ }).throw()
+ })
+
+ it('should authenticate by passing clientId and clientSecret in an object', function(done) {
+ var isolatedClient = new UsergridClient()
+ isolatedClient.authenticateApp(config, function(err, reponse, token) {
+ isolatedClient.appAuth.should.have.property('token').equal(token)
+ done()
+ })
+ })
+
+ it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using an object)', function(done) {
+ var failClient = new UsergridClient()
+ failClient.authenticateApp(new UsergridAppAuth({
+ clientId: 'BADCLIENTID',
+ clientSecret: 'BADCLIENTSECRET'
+ }), function(e, r, token) {
+ should(token).be.undefined()
+ should(failClient.appAuth).be.undefined()
+ done()
+ })
+ })
+
+ it('should not set client.appAuth when authenticating with a bad UsergridAppAuth instance (using arguments)', function(done) {
+ var failClient = new UsergridClient()
+ failClient.authenticateApp(new UsergridAppAuth('BADCLIENTID', 'BADCLIENTSECRET'), function(e, r, token) {
+ should(token).be.undefined()
+ should(failClient.appAuth).be.undefined()
+ done()
+ })
+ })
+
+ it('response.ok should be true', function() {
+ response.ok.should.be.true()
+ })
+
+ it('should have a valid token', function() {
+ token.should.be.a.String()
+ token.length.should.be.greaterThan(10)
+ })
+
+ it('client.appAuth.token should be set to the token returned from Usergrid', function() {
+ client.appAuth.should.have.property('token').equal(token)
+ })
+
+ it('client.appAuth.isValid should be true', function() {
+ client.appAuth.should.have.property('isValid').which.is.true()
+ })
+
+ it('client.appAuth.expiry should be set to a future date', function() {
+ client.appAuth.should.have.property('expiry').greaterThan(Date.now())
+ })
+})
+
+describe('authenticateUser()', function() {
+
+ this.slow(_slow)
+ this.timeout(_timeout)
+
+ var response, token, client = new UsergridClient()
+ before(function(done) {
+ client.authenticateUser({
+ username: config.test.username,
+ password: config.test.password
+ }, function(err, r, t) {
+ response = r
+ token = t
+ done()
+ })
+ })
+
+ it('should fail when called without a email (or username) and password', function() {
+ should(function() {
+ var client = new UsergridClient()
+ client.authenticateUser({})
+ }).throw()
+ })
+
+ it('response.ok should be true', function() {
+ response.ok.should.be.true()
+ })
+
+ it('should have a valid token', function() {
+ token.should.be.a.String()
+ token.length.should.be.greaterThan(10)
+ })
+
+ it('client.currentUser.auth.token should be set to the token returned from Usergrid', function() {
+ client.currentUser.auth.should.have.property('token').equal(token)
+ })
+
+ it('client.currentUser.auth.isValid should be true', function() {
+ client.currentUser.auth.should.have.property('isValid').which.is.true()
+ })
+
+ it('client.currentUser.auth.expiry should be set to a future date', function() {
+ client.currentUser.auth.should.have.property('expiry').greaterThan(Date.now())
+ })
+
+ it('client.currentUser should have a username', function() {
+ client.currentUser.should.have.property('username')
+ })
+
+ it('client.currentUser should have an email', function() {
+ client.currentUser.should.have.property('email')
+ })
+
+ it('client.currentUser and client.currentUser.auth should not store password', function() {
+ client.currentUser.should.not.have.property('password')
+ client.currentUser.auth.should.not.have.property('password')
+ })
+})
+
+describe('appAuth, setAppAuth()', function() {
+ it('should initialize by passing a list of arguments', function() {
+ var client = new UsergridClient()
+ client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl)
+ client.appAuth.should.be.instanceof(UsergridAppAuth)
+ })
+
+ it('should be a subclass of UsergridAuth', function() {
+ var client = new UsergridClient()
+ client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl)
+ client.appAuth.should.be.instanceof(UsergridAuth)
+ })
+
+ it('should initialize by passing an object', function() {
+ var client = new UsergridClient()
+ client.setAppAuth({
+ clientId: config.clientId,
+ clientSecret: config.clientSecret,
+ tokenTtl: config.tokenTtl
+ })
+ client.appAuth.should.be.instanceof(UsergridAppAuth)
+ })
+
+ it('should initialize by passing an instance of UsergridAppAuth', function() {
+ var client = new UsergridClient()
+ client.setAppAuth(new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl))
+ client.appAuth.should.be.instanceof(UsergridAppAuth)
+ })
+
+ it('should initialize by setting to an instance of UsergridAppAuth', function() {
+ var client = new UsergridClient()
+ client.appAuth = new UsergridAppAuth(config.clientId, config.clientSecret, config.tokenTtl)
+ client.appAuth.should.be.instanceof(UsergridAppAuth)
+ })
+})
\ No newline at end of file
diff --git a/tests/lib/entity.test.js b/tests/lib/entity.test.js
index faee854..94e69e9 100644
--- a/tests/lib/entity.test.js
+++ b/tests/lib/entity.test.js
@@ -358,7 +358,7 @@
}, function(err, postResponse) {
var entity = new UsergridEntity(postResponse.first)
entity.remove(function(err, deleteResponse) {
- deleteResponse.statusCode.should.equal(200)
+ deleteResponse.ok.should.be.true()
// best practice is to delete the entity object here, because it no longer exists on the server
entity = null
done()
@@ -373,7 +373,7 @@
}, function(err, postResponse) {
var entity = new UsergridEntity(postResponse.first)
entity.remove(client, function(err, deleteResponse) {
- deleteResponse.statusCode.should.equal(200)
+ deleteResponse.ok.should.be.true()
// best practice is to delete the entity object here, because it no longer exists on the server
entity = null
done()
@@ -413,7 +413,7 @@
var relationship = "foos"
entity1.connect(relationship, entity2, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[relationship].should.equal(urljoin(
"/",
@@ -433,7 +433,7 @@
var relationship = "bars"
entity1.connect(relationship, entity2.uuid, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[relationship].should.equal(urljoin(
"/",
@@ -453,7 +453,7 @@
var relationship = "bazzes"
entity1.connect(relationship, entity2.type, entity2.name, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.first.metadata.connecting[relationship].should.equal(urljoin(
"/",
@@ -555,7 +555,7 @@
var relationship = "foos"
entity1.disconnect(relationship, entity2, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.entities.should.be.an.Array().with.lengthOf(0)
done()
@@ -570,7 +570,7 @@
var relationship = "bars"
entity1.disconnect(relationship, entity2.uuid, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.entities.should.be.an.Array().with.lengthOf(0)
done()
@@ -585,7 +585,7 @@
var relationship = "bazzes"
client.disconnect(entity1.type, entity1.name, relationship, entity2.type, entity2.name, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
client.getConnections(UsergridClient.Connections.DIRECTION_OUT, entity1, relationship, function(err, usergridResponse) {
usergridResponse.entities.should.be.an.Array().with.lengthOf(0)
done()
diff --git a/tests/lib/response.test.js b/tests/lib/response.test.js
index 2672153..e24f2c5 100644
--- a/tests/lib/response.test.js
+++ b/tests/lib/response.test.js
@@ -39,6 +39,12 @@
})
})
+describe('ok', function() {
+ it('should be a bool', function() {
+ _response.ok.should.be.a.Boolean()
+ })
+})
+
describe('metadata', function() {
it('should be a read-only object', function() {
_response.metadata.should.be.an.Object().with.any.properties(['action', 'application', 'path', 'uri', 'timestamp', 'duration'])
@@ -70,9 +76,9 @@
it('response.users should be an array of UsergridUser objects', function(done) {
client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl)
client.authenticateApp(function(err, response) {
- should(err).be.null()
+ should(err).be.undefined()
client.GET('users', function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
usergridResponse.users.should.be.an.Array()
usergridResponse.users.forEach(function(user) {
user.should.be.an.instanceof(UsergridUser)
@@ -93,7 +99,7 @@
it('response.user should be a UsergridUser object and have a valid uuid matching the first object in response.users', function(done) {
client.setAppAuth(config.clientId, config.clientSecret, config.tokenTtl)
client.authenticateApp(function(err) {
- should(err).be.null()
+ should(err).be.undefined()
client.GET('users', function(err, usergridResponse) {
user = usergridResponse.user
user.should.be.an.instanceof(UsergridUser).with.property('uuid').equal(_.first(usergridResponse.entities).uuid)
diff --git a/tests/lib/responseError.test.js b/tests/lib/responseError.test.js
index 27a7967..6e0c3c9 100644
--- a/tests/lib/responseError.test.js
+++ b/tests/lib/responseError.test.js
@@ -25,11 +25,11 @@
})
it('response.statusCode should be greater than or equal to 400', function() {
- _response.statusCode.should.be.greaterThanOrEqual(400)
+ _response.ok.should.be.false()
})
it('response.error should be a UsergridResponseError object with name, description, and exception keys', function() {
- _response.statusCode.should.not.equal(200)
+ _response.ok.should.be.false()
_response.error.should.be.an.instanceof(UsergridResponseError).with.keys(['name', 'description', 'exception'])
})
})
@@ -39,7 +39,7 @@
this.slow(_slow)
this.timeout(_timeout)
client.GET(config.test.collection, function(err, usergridResponse) {
- usergridResponse.statusCode.should.equal(200)
+ usergridResponse.ok.should.be.true()
should(usergridResponse.error).be.undefined()
done()
})
diff --git a/tests/lib/user.test.js b/tests/lib/user.test.js
index abcfa81..8a59787 100644
--- a/tests/lib/user.test.js
+++ b/tests/lib/user.test.js
@@ -10,8 +10,6 @@
UsergridQuery = require('../../lib/query'),
_ = require('lodash')
-_.mixin(require('lodash-uuid'))
-
var _slow = 1500,
_timeout = 4000,
_username1 = chance.word(),
@@ -25,8 +23,13 @@
this.slow(_slow)
this.timeout(_timeout)
- _user1.create(function(err, usergridResponse, user) {
- done()
+ var client = new UsergridClient()
+ var query = new UsergridQuery('users').not.eq('username', config.test.username).limit(20)
+ // clean up old user entities as the UsergridResponse tests rely on this collection containing less than 10 entities
+ client.DELETE(query, function() {
+ _user1.create(function(err, usergridResponse, user) {
+ done()
+ })
})
})
@@ -111,7 +114,7 @@
it(util.format("it should log out '%s' and destroy the saved UsergridUserAuth instance", _username1), function(done) {
_user1.logout(function(err, response, success) {
- response.statusCode.should.equal(200)
+ response.ok.should.be.true()
response.body.action.should.equal("revoked user token")
_user1.auth.isValid.should.be.false()
done()
@@ -122,7 +125,7 @@
_user1.password = config.test.password
_user1.login(function(err, response, token) {
_user1.logoutAllSessions(function(err, response, success) {
- response.statusCode.should.equal(200)
+ response.ok.should.be.true()
response.body.action.should.equal("revoked user tokens")
_user1.auth.isValid.should.be.false()
done()
@@ -147,7 +150,7 @@
it(util.format("it should reset the password for '%s' by passing parameters", _username1), function(done) {
_user1.resetPassword(config.test.password, '2cool4u', function(err, response, success) {
- response.statusCode.should.equal(200)
+ response.ok.should.be.true()
response.body.action.should.equal("set user password")
done()
})
@@ -158,7 +161,7 @@
oldPassword: '2cool4u',
newPassword: config.test.password
}, function(err, response, success) {
- response.statusCode.should.equal(200)
+ response.ok.should.be.true()
response.body.action.should.equal("set user password")
done()
})
diff --git a/tests/main.test.js b/tests/main.test.js
index 7814a5c..8cd06c0 100644
--- a/tests/main.test.js
+++ b/tests/main.test.js
@@ -10,7 +10,7 @@
this.params = {
operator: 'to be a valid uuid'
};
- this.assert(_.isUuid(this.obj));
+ this.assert(_.isUuid(this.obj))
})
// end module config