From 93bb0e9097d27bf9ea8e72532054a017f16af2a9 Mon Sep 17 00:00:00 2001 From: Chris Allard Date: Thu, 11 Jul 2013 15:38:38 +0200 Subject: [PATCH] API method: user.getAll(). --- src/api.js | 24 ++++++++++++++++++++++-- src/collection.js | 28 +++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/api.js b/src/api.js index 36f6901..60e896c 100644 --- a/src/api.js +++ b/src/api.js @@ -289,8 +289,28 @@ Api.fn.user = { }, - 'getAll': function () { - throw Api.err.NOT_IMPLEMENTED; + 'getAll': function (session) { + var user_id = session.get('user_id'); + if (undefined === user_id) + { + throw Api.err.UNAUTHORIZED; + } + + var users = this.users; + return users.get(user_id).then(function (user) { + if (!user.hasPermission('admin')) + { + throw Api.err.UNAUTHORIZED; + } + + return users.where(); + }).then(function (all_users) { + _.each(all_users, function (user, i) { + all_users[i] = _.pick(user, 'id', 'email', 'permission'); + }); + + return all_users; + }); }, 'set': function (session, request) { diff --git a/src/collection.js b/src/collection.js index c5c9741..fc2708d 100644 --- a/src/collection.js +++ b/src/collection.js @@ -89,7 +89,7 @@ Collection.prototype.exists = function (id) { }; /** - * + * Find the first model which has a given set of properties. */ Collection.prototype.findWhere = function (properties) { /* jshint newcap: false */ @@ -99,6 +99,32 @@ Collection.prototype.findWhere = function (properties) { return Q(model ? new this.model(model) : null); }; + +/** + * Find all models which have a given set of properties. + * + * /!\: Does not return instance of this.model. + */ +Collection.prototype.where = function (properties) { + /* jshint newcap: false */ + if (_.isEmpty(properties)) + { + return Q(this.models.slice()); + } + + return Q(_.filter(this.models, function (model) { + for (var property in properties) + { + if (model[property] !== properties[property]) + { + return false; + } + } + return true; + })); +}; + + /** * Removes models from this collection. */