IGNITE-3262 Refactored  Space Service. Added new tests.

Project: http://git-wip-us.apache.org/repos/asf/ignite/repo
Commit: http://git-wip-us.apache.org/repos/asf/ignite/commit/cac7d967
Tree: http://git-wip-us.apache.org/repos/asf/ignite/tree/cac7d967
Diff: http://git-wip-us.apache.org/repos/asf/ignite/diff/cac7d967

Branch: refs/heads/ignite-3262
Commit: cac7d96761e283bcfcc8dabbae13948bf6cb1844
Parents: 2e6a518
Author: Maxim Afanasiev <[email protected]>
Authored: Thu Jun 30 17:51:14 2016 +0700
Committer: Maxim Afanasiev <[email protected]>
Committed: Thu Jun 30 17:51:14 2016 +0700

----------------------------------------------------------------------
 .../js/serve/errors/IllegalArgumentException.js |  29 +++++
 .../main/js/serve/errors/NotFoundException.js   |  29 +++++
 .../src/main/js/serve/errors/index.js           |   4 +-
 modules/web-console/src/main/js/serve/mongo.js  |  30 +----
 .../src/main/js/serve/routes/admin.js           |   6 +-
 .../src/main/js/serve/routes/caches.js          |   2 +-
 .../src/main/js/serve/routes/clusters.js        |   8 +-
 .../src/main/js/serve/routes/demo.js            |   7 +-
 .../src/main/js/serve/routes/domains.js         |   8 +-
 .../src/main/js/serve/routes/igfs.js            |   8 +-
 .../src/main/js/serve/routes/notebooks.js       |  10 +-
 .../src/main/js/serve/services/cache.js         |  26 ++--
 .../src/main/js/serve/services/space.js         |  19 +--
 .../src/main/js/test/backend/data/spaces.json   |  18 ---
 .../js/test/backend/unit/CacheService.test.js   | 121 ++++++++++++++-----
 15 files changed, 203 insertions(+), 122 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/errors/IllegalArgumentException.js
----------------------------------------------------------------------
diff --git 
a/modules/web-console/src/main/js/serve/errors/IllegalArgumentException.js 
b/modules/web-console/src/main/js/serve/errors/IllegalArgumentException.js
new file mode 100644
index 0000000..0487d05
--- /dev/null
+++ b/modules/web-console/src/main/js/serve/errors/IllegalArgumentException.js
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+'use strict';
+
+import AppErrorException from './AppErrorException';
+
+class IllegalArgumentException extends AppErrorException {
+    constructor(message) {
+        super(message);
+        this.httpCode = 400;
+    }
+}
+
+module.exports = IllegalArgumentException;

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/errors/NotFoundException.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/errors/NotFoundException.js 
b/modules/web-console/src/main/js/serve/errors/NotFoundException.js
new file mode 100644
index 0000000..2e0fdd6
--- /dev/null
+++ b/modules/web-console/src/main/js/serve/errors/NotFoundException.js
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.
+ */
+
+'use strict';
+
+import AppErrorException from './AppErrorException';
+
+class NotFoundException extends AppErrorException {
+    constructor(message) {
+        super(message);
+        this.httpCode = 404;
+    }
+}
+
+module.exports = NotFoundException;

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/errors/index.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/errors/index.js 
b/modules/web-console/src/main/js/serve/errors/index.js
index 9e3a1b0..011883a 100644
--- a/modules/web-console/src/main/js/serve/errors/index.js
+++ b/modules/web-console/src/main/js/serve/errors/index.js
@@ -23,7 +23,9 @@ module.exports = {
     implements: 'errors',
     factory: () => ({
         AppErrorException: require('./AppErrorException'),
+        IllegalArgumentException: require('./IllegalArgumentException'),
         DuplicateKeyException: require('./DuplicateKeyException'),
-        ServerErrorException: require('./ServerErrorException')
+        ServerErrorException: require('./ServerErrorException'),
+        NotFoundException: require('./NotFoundException')
     })
 };

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/mongo.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/mongo.js 
b/modules/web-console/src/main/js/serve/mongo.js
index 8c7cfaa..1f203b7 100644
--- a/modules/web-console/src/main/js/serve/mongo.js
+++ b/modules/web-console/src/main/js/serve/mongo.js
@@ -133,8 +133,8 @@ module.exports.factory = function(deepPopulatePlugin, 
passportMongo, settings, p
 
     // Define Cache schema.
     const CacheSchema = new Schema({
-        space: {type: ObjectId, ref: 'Space', index: true, required: true},
-        name: {type: String, required: true},
+        space: {type: ObjectId, ref: 'Space', index: true},
+        name: {type: String},
         clusters: [{type: ObjectId, ref: 'Cluster'}],
         domains: [{type: ObjectId, ref: 'DomainModel'}],
         cacheMode: {type: String, enum: ['PARTITIONED', 'REPLICATED', 
'LOCAL']},
@@ -216,7 +216,7 @@ module.exports.factory = function(deepPopulatePlugin, 
passportMongo, settings, p
         writeBehindFlushFrequency: Number,
         writeBehindFlushThreadCount: Number,
 
-        // invalidate: Boolean,
+        invalidate: Boolean,
         defaultLockTimeout: Number,
         atomicWriteOrderMode: {type: String, enum: ['CLOCK', 'PRIMARY']},
         writeSynchronizationMode: {type: String, enum: ['FULL_SYNC', 
'FULL_ASYNC', 'PRIMARY_SYNC']},
@@ -648,30 +648,6 @@ module.exports.factory = function(deepPopulatePlugin, 
passportMongo, settings, p
     };
 
 
-    // TODO Remove after refactoring spaceService.
-    /**
-     * Query for user spaces.
-     *
-     * @param userId User ID.
-     * @param {Boolean} demo Is need use demo space.
-     * @returns {Promise}
-     */
-    result.spaces = function(userId, demo) {
-        return result.Space.find({owner: userId, demo: !!demo}).lean().exec();
-    };
-
-    /**
-     * Extract IDs from user spaces.
-     *
-     * @param userId User ID.
-     * @param {Boolean} demo Is need use demo space.
-     * @returns {Promise}
-     */
-    result.spaceIds = function(userId, demo) {
-        return result.spaces(userId, demo)
-            .then((spaces) => spaces.map((space) => space._id));
-    };
-
     // Registering the routes of all plugin modules
     for (const name in pluginMongo) {
         if (pluginMongo.hasOwnProperty(name))

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/routes/admin.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/routes/admin.js 
b/modules/web-console/src/main/js/serve/routes/admin.js
index 3c2e728..791e935 100644
--- a/modules/web-console/src/main/js/serve/routes/admin.js
+++ b/modules/web-console/src/main/js/serve/routes/admin.js
@@ -21,10 +21,10 @@
 
 module.exports = {
     implements: 'admin-routes',
-    inject: ['require(lodash)', 'require(express)', 'settings', 'mail', 
'mongo']
+    inject: ['require(lodash)', 'require(express)', 'settings', 'mail', 
'mongo', 'services/space']
 };
 
-module.exports.factory = function(_, express, settings, mail, mongo) {
+module.exports.factory = function(_, express, settings, mail, mongo, 
spaceService) {
     return new Promise((factoryResolve) => {
         const router = new express.Router();
 
@@ -72,7 +72,7 @@ module.exports.factory = function(_, express, settings, mail, 
mongo) {
                 .then((user) => {
                     res.sendStatus(200);
 
-                    return mongo.spaceIds(userId)
+                    return spaceService.spaceIds(userId)
                         .then((spaceIds) => Promise.all([
                             mongo.Cluster.remove({space: {$in: 
spaceIds}}).exec(),
                             mongo.Cache.remove({space: {$in: 
spaceIds}}).exec(),

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/routes/caches.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/routes/caches.js 
b/modules/web-console/src/main/js/serve/routes/caches.js
index aa25288..334b7f2 100644
--- a/modules/web-console/src/main/js/serve/routes/caches.js
+++ b/modules/web-console/src/main/js/serve/routes/caches.js
@@ -54,7 +54,7 @@ module.exports.factory = function(_, express, mongo, 
cacheService) {
         router.post('/remove', (req, res) => {
             const cache = req.body;
 
-            cacheService.remove(cache)
+            cacheService.remove(cache._id)
                 .then(res.api.ok)
                 .catch(res.api.error);
         });

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/routes/clusters.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/routes/clusters.js 
b/modules/web-console/src/main/js/serve/routes/clusters.js
index 9d13990..6cb5385 100644
--- a/modules/web-console/src/main/js/serve/routes/clusters.js
+++ b/modules/web-console/src/main/js/serve/routes/clusters.js
@@ -21,10 +21,10 @@
 
 module.exports = {
     implements: 'clusters-routes',
-    inject: ['require(lodash)', 'require(express)', 'mongo']
+    inject: ['require(lodash)', 'require(express)', 'mongo', 'services/space']
 };
 
-module.exports.factory = function(_, express, mongo) {
+module.exports.factory = function(_, express, mongo, spaceService) {
     return new Promise((factoryResolve) => {
         const router = new express.Router();
 
@@ -39,7 +39,7 @@ module.exports.factory = function(_, express, mongo) {
             let spaceIds = [];
             let domains = {};
 
-            mongo.spaces(req.currentUserId(), req.header('IgniteDemoMode'))
+            spaceService.spaces(req.currentUserId(), 
req.header('IgniteDemoMode'))
                 .then((spaces) => {
                     result.spaces = spaces;
                     spaceIds = spaces.map((space) => space._id);
@@ -132,7 +132,7 @@ module.exports.factory = function(_, express, mongo) {
          */
         router.post('/remove/all', (req, res) => {
             // Get owned space and all accessed space.
-            mongo.spaceIds(req.currentUserId(), req.header('IgniteDemoMode'))
+            spaceService.spaceIds(req.currentUserId(), 
req.header('IgniteDemoMode'))
                 .then((spaceIds) => mongo.Cache.update({space: {$in: 
spaceIds}}, {clusters: []}, {multi: true}).exec()
                     .then(() => mongo.Igfs.update({space: {$in: spaceIds}}, 
{clusters: []}, {multi: true}).exec())
                     .then(() => mongo.Cluster.remove({space: {$in: 
spaceIds}}).exec())

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/routes/demo.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/routes/demo.js 
b/modules/web-console/src/main/js/serve/routes/demo.js
index dd47eb9..e49c2f9 100644
--- a/modules/web-console/src/main/js/serve/routes/demo.js
+++ b/modules/web-console/src/main/js/serve/routes/demo.js
@@ -29,11 +29,12 @@ module.exports = {
         'require(./demo/domains.json)',
         'require(./demo/caches.json)',
         'require(./demo/igfss.json)',
-        'require(./demo/clusters.json)'
+        'require(./demo/clusters.json)',
+        'services/space'
     ]
 };
 
-module.exports.factory = (_, express, settings, mongo, domains, caches, igfss, 
clusters) => {
+module.exports.factory = (_, express, settings, mongo, domains, caches, igfss, 
clusters, spaceService) => {
     return new Promise((factoryResolve) => {
         const router = new express.Router();
 
@@ -41,7 +42,7 @@ module.exports.factory = (_, express, settings, mongo, 
domains, caches, igfss, c
          * Reset demo configuration.
          */
         router.post('/reset', (req, res) => {
-            mongo.spaces(req.user._id, true)
+            spaceService.spaces(req.user._id, true)
                 .then((spaces) => {
                     if (spaces.length) {
                         const spaceIds = spaces.map((space) => space._id);

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/routes/domains.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/routes/domains.js 
b/modules/web-console/src/main/js/serve/routes/domains.js
index 9dbf418..d1d402f 100644
--- a/modules/web-console/src/main/js/serve/routes/domains.js
+++ b/modules/web-console/src/main/js/serve/routes/domains.js
@@ -21,10 +21,10 @@
 
 module.exports = {
     implements: 'domains-routes',
-    inject: ['require(lodash)', 'require(express)', 'mongo']
+    inject: ['require(lodash)', 'require(express)', 'mongo', 'services/space']
 };
 
-module.exports.factory = (_, express, mongo) => {
+module.exports.factory = (_, express, mongo, spaceService) => {
     return new Promise((factoryResolve) => {
         const router = new express.Router();
 
@@ -38,7 +38,7 @@ module.exports.factory = (_, express, mongo) => {
             const result = {};
             let spacesIds = [];
 
-            mongo.spaces(req.currentUserId(), req.header('IgniteDemoMode'))
+            spaceService.spaces(req.currentUserId(), 
req.header('IgniteDemoMode'))
                 .then((spaces) => {
                     result.spaces = spaces;
                     spacesIds = spaces.map((space) => space._id);
@@ -182,7 +182,7 @@ module.exports.factory = (_, express, mongo) => {
          * Remove all domain models.
          */
         router.post('/remove/all', (req, res) => {
-            mongo.spaceIds(req.currentUserId(), req.header('IgniteDemoMode'))
+            spaceService.spaceIds(req.currentUserId(), 
req.header('IgniteDemoMode'))
                 .then((spaceIds) => mongo.Cache.update({space: {$in: 
spaceIds}}, {domains: []}, {multi: true}).exec()
                         .then(() => mongo.DomainModel.remove({space: {$in: 
spaceIds}}).exec()))
                 .then(() => res.sendStatus(200))

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/routes/igfs.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/routes/igfs.js 
b/modules/web-console/src/main/js/serve/routes/igfs.js
index f590273..e44d8c2 100644
--- a/modules/web-console/src/main/js/serve/routes/igfs.js
+++ b/modules/web-console/src/main/js/serve/routes/igfs.js
@@ -21,10 +21,10 @@
 
 module.exports = {
     implements: 'igfs-routes',
-    inject: ['require(lodash)', 'require(express)', 'mongo']
+    inject: ['require(lodash)', 'require(express)', 'mongo', 'services/space']
 };
 
-module.exports.factory = function(_, express, mongo) {
+module.exports.factory = function(_, express, mongo, spaceService) {
     return new Promise((factoryResolve) => {
         const router = new express.Router();
 
@@ -39,7 +39,7 @@ module.exports.factory = function(_, express, mongo) {
             let spaceIds = [];
 
             // Get owned space and all accessed space.
-            mongo.spaces(req.currentUserId(), req.header('IgniteDemoMode'))
+            spaceService.spaces(req.currentUserId(), 
req.header('IgniteDemoMode'))
                 .then((spaces) => {
                     result.spaces = spaces;
                     spaceIds = spaces.map((space) => space._id);
@@ -107,7 +107,7 @@ module.exports.factory = function(_, express, mongo) {
          */
         router.post('/remove/all', (req, res) => {
             // Get owned space and all accessed space.
-            mongo.spaceIds(req.currentUserId(), req.header('IgniteDemoMode'))
+            spaceService.spaceIds(req.currentUserId(), 
req.header('IgniteDemoMode'))
                 .then((spaceIds) =>
                     mongo.Cluster.update({space: {$in: spaceIds}}, {igfss: 
[]}, {multi: true}).exec()
                         .then(() => mongo.Igfs.remove({space: {$in: 
spaceIds}}).exec())

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/routes/notebooks.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/routes/notebooks.js 
b/modules/web-console/src/main/js/serve/routes/notebooks.js
index 37665bf..6b8faff 100644
--- a/modules/web-console/src/main/js/serve/routes/notebooks.js
+++ b/modules/web-console/src/main/js/serve/routes/notebooks.js
@@ -21,10 +21,10 @@
 
 module.exports = {
     implements: 'notebooks-routes',
-    inject: ['require(express)', 'mongo']
+    inject: ['require(express)', 'mongo', 'services/space']
 };
 
-module.exports.factory = function(express, mongo) {
+module.exports.factory = function(express, mongo, spaceService) {
     return new Promise((factoryResolve) => {
         const router = new express.Router();
 
@@ -35,7 +35,7 @@ module.exports.factory = function(express, mongo) {
          * @param res Response.
          */
         router.post('/list', (req, res) => {
-            mongo.spaces(req.currentUserId())
+            spaceService.spaces(req.currentUserId())
                 .then((spaces) => mongo.Notebook.find({space: {$in: 
spaces.map((value) => value._id)}}).select('_id 
name').sort('name').lean().exec())
                 .then((notebooks) => res.json(notebooks))
                 .catch((err) => mongo.handleError(res, err));
@@ -49,7 +49,7 @@ module.exports.factory = function(express, mongo) {
          * @param res Response.
          */
         router.post('/get', (req, res) => {
-            mongo.spaces(req.currentUserId())
+            spaceService.spaces(req.currentUserId())
                 .then((spaces) => mongo.Notebook.findOne({space: {$in: 
spaces.map((value) => value._id)}, _id: req.body.noteId}).lean().exec())
                 .then((notebook) => res.json(notebook))
                 .catch((err) => mongo.handleError(res, err));
@@ -102,7 +102,7 @@ module.exports.factory = function(express, mongo) {
          * @param res Response.
          */
         router.post('/new', (req, res) => {
-            mongo.spaceIds(req.currentUserId())
+            spaceService.spaceIds(req.currentUserId())
                 .then((spaceIds) =>
                     mongo.Notebook.findOne({space: spaceIds[0], name: 
req.body.name})
                         .then((notebook) => {

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/services/cache.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/services/cache.js 
b/modules/web-console/src/main/js/serve/services/cache.js
index c4aa39a..94a85ad 100644
--- a/modules/web-console/src/main/js/serve/services/cache.js
+++ b/modules/web-console/src/main/js/serve/services/cache.js
@@ -23,12 +23,11 @@ module.exports = {
     implements: 'services/cache',
     inject: ['require(lodash)',
         'mongo',
+        'services/space',
         'errors']
 };
 
-module.exports.factory = (_, mongo, errors) => {
-
-
+module.exports.factory = (_, mongo, spaceService, errors) => {
     /**
      * Convert remove status operation to own presentation.
      * @param {RemoveResult} result - The results of remove operation.
@@ -78,7 +77,6 @@ module.exports.factory = (_, mongo, errors) => {
         return mongo.Cluster.update({space: {$in: spaceIds}}, {caches: []}, 
{multi: true}).exec()
             .then(() => mongo.DomainModel.update({space: {$in: spaceIds}}, 
{caches: []}, {multi: true}).exec())
             .then(() => mongo.Cache.remove({space: {$in: spaceIds}}).exec())
-            .then(convertRemoveStatus)
     };
 
     /**
@@ -99,13 +97,13 @@ module.exports.factory = (_, mongo, errors) => {
 
         /**
          * Get caches and linked objects by user.
-         * @param {Integer} userId - The user id that own caches.
+         * @param {mongo.ObjectId|String} userId - The user id that own caches.
          * @param {Boolean} demo - The flag indicates that need lookup in demo 
space.
          * @returns {Promise.<[mongo.Cache[], mongo.Cluster[], 
mongo.DomainModel[], mongo.Space[]]>} - contains requested caches and array of 
linked objects: clusters, domains, spaces.
          */
         static listByUser(userId, demo) {
             // Get owned space and all accessed space.
-            return mongo.spaces(userId, demo)
+            return spaceService.spaces(userId, demo)
                 .then((spaces) => {
                     const spaceIds = spaces.map((space) => space._id);
 
@@ -120,27 +118,29 @@ module.exports.factory = (_, mongo, errors) => {
 
         /**
          * Remove cache.
-         * @param {Object} cache - The cache object with _id property.
+         * @param {mongo.ObjectId|String} cacheId - The cache id for remove.
          * @returns {Promise.<{rowsAffected}>} - The number of affected rows.
          */
-        static remove(cache) {
-            const cacheId = cache._id;
+        static remove(cacheId) {
+            if(!cacheId)
+                throw new errors.IllegalArgumentException('Cache id can not be 
undefined or null');
 
             return mongo.Cluster.update({caches: {$in: [cacheId]}}, {$pull: 
{caches: cacheId}}, {multi: true}).exec()
                 .then(() => mongo.DomainModel.update({caches: {$in: 
[cacheId]}}, {$pull: {caches: cacheId}}, {multi: true}).exec())
-                .then(() => mongo.Cache.remove(cache).exec())
+                .then(() => mongo.Cache.remove({_id: cacheId}).exec())
                 .then(convertRemoveStatus);
         }
 
         /**
          * Remove all caches by user.
-         * @param {Integer} userId - The user id that own caches.
+         * @param {mongo.ObjectId|String} userId - The user id that own caches.
          * @param {Boolean} demo - The flag indicates that need lookup in demo 
space.
          * @returns {Promise.<{rowsAffected}>} - The number of affected rows.
          */
         static removeAll(userId, demo) {
-            return mongo.spaceIds(userId, demo)
-                .then(removeAllBySpaces);
+            return spaceService.spaceIds(userId, demo)
+                .then(removeAllBySpaces)
+                .then(convertRemoveStatus);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/serve/services/space.js
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/serve/services/space.js 
b/modules/web-console/src/main/js/serve/services/space.js
index 106a0cb..d6a069f 100644
--- a/modules/web-console/src/main/js/serve/services/space.js
+++ b/modules/web-console/src/main/js/serve/services/space.js
@@ -20,33 +20,38 @@
 // Fire me up!
 
 module.exports = {
-    implements: 'services/spaceService',
+    implements: 'services/space',
     inject: ['mongo']
 };
 
 module.exports.factory = (mongo) => {
 
     class SpaceService {
-
         /**
          * Query for user spaces.
          *
-         * @param userId User ID.
+         * @param {mongo.ObjectId|String} userId User ID.
          * @param {Boolean} demo Is need use demo space.
          * @returns {Promise}
          */
-        spaces(userId, demo) {
-            return mongo.Space.find({owner: userId, demo: 
!!demo}).lean().exec();
+        static spaces(userId, demo) {
+            return mongo.Space.find({owner: userId, demo: 
!!demo}).lean().exec()
+                .then((spaces) => {
+                    if (!spaces.length)
+                        throw new errors.NotFoundException('Spaces not found');
+
+                    return spaces;
+                });
         }
 
         /**
          * Extract IDs from user spaces.
          *
-         * @param userId User ID.
+         * @param {mongo.ObjectId|String} userId User ID.
          * @param {Boolean} demo Is need use demo space.
          * @returns {Promise}
          */
-        spaceIds(userId, demo) {
+        static spaceIds(userId, demo) {
             return this.spaces(userId, demo)
                 .then((spaces) => spaces.map((space) => space._id));
         }

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/test/backend/data/spaces.json
----------------------------------------------------------------------
diff --git a/modules/web-console/src/main/js/test/backend/data/spaces.json 
b/modules/web-console/src/main/js/test/backend/data/spaces.json
deleted file mode 100644
index edbb633..0000000
--- a/modules/web-console/src/main/js/test/backend/data/spaces.json
+++ /dev/null
@@ -1,18 +0,0 @@
-[
-  {
-    "_id" : "57725444e6d604c05dab9dee",
-    "name" : "Personal space",
-    "owner" : "57725443e6d604c05dab9ded",
-    "usedBy" : [],
-    "demo" : false,
-    "__v" : 0
-  },
-  {
-    "_id" : "5772545be6d604c05dab9def",
-    "name" : "Demo space",
-    "owner" : "57725443e6d604c05dab9ded",
-    "usedBy" : [],
-    "demo" : true,
-    "__v" : 0
-  }
-]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/ignite/blob/cac7d967/modules/web-console/src/main/js/test/backend/unit/CacheService.test.js
----------------------------------------------------------------------
diff --git 
a/modules/web-console/src/main/js/test/backend/unit/CacheService.test.js 
b/modules/web-console/src/main/js/test/backend/unit/CacheService.test.js
index b597ff0..d75c72a 100644
--- a/modules/web-console/src/main/js/test/backend/unit/CacheService.test.js
+++ b/modules/web-console/src/main/js/test/backend/unit/CacheService.test.js
@@ -20,7 +20,6 @@ import {assert} from 'chai';
 import fireUp from '../injector';
 import testCaches from '../data/caches.json';
 import testAccounts from '../data/accounts.json';
-import testSpaces from '../data/spaces.json';
 
 let cacheService;
 let mongo;
@@ -28,8 +27,19 @@ let errors;
 
 suite('CacheService', () => {
 
-    const injectSpaceInCaches = (spaceId) => {
-        return testCaches.map((cache) => ({...cache, space: spaceId}));
+    const prepareUserSpaces = () => {
+        return mongo.Account.create(testAccounts)
+            .then((accounts) => {
+                return Promise.all(accounts.map((account)=> {
+                    return mongo.Space.create([
+                        {name: 'Personal space', owner: account._id, demo: 
false},
+                        {name: 'Demo space', owner: account._id, demo: true}
+                    ])
+                }))
+                    .then((spaces)=> {
+                        return [accounts, spaces];
+                    });
+            });
     };
 
     suiteSetup(() => {
@@ -43,12 +53,14 @@ suite('CacheService', () => {
 
     setup(() => {
         return Promise.all([
-            mongo.Cache.remove().exec()
+            mongo.Cache.remove().exec(),
+            mongo.Account.remove().exec(),
+            mongo.Space.remove().exec()
         ]);
     });
 
-    test('Cache merge', (done) => {
-        return cacheService.merge(testCaches[0])
+    test('Cache merge.', (done) => {
+        cacheService.merge(testCaches[0])
             .then((cacheId) => {
                 assert.isNotNull(cacheId);
 
@@ -58,43 +70,45 @@ suite('CacheService', () => {
                 return mongo.Cache.findById(cacheId)
                     .then((cache) => {
                         assert.isNotNull(cache);
-                    });
+                    })
             })
             .then(done)
             .catch(done);
     });
 
     test('Try to save same cache twice.', (done) => {
-        return cacheService.merge(testCaches[0])
+        cacheService.merge(testCaches[0])
             .then(() => cacheService.merge(testCaches[0]))
             .catch((err) => {
                 assert.instanceOf(err, errors.DuplicateKeyException);
                 done();
-            })
-            .then(done);
-    });
-
-    test('Try to save null cache.', (done) => {
-        return cacheService.merge({})
-            .then(done)
-            .catch((err) => {
-                assert.instanceOf(err, errors.DuplicateKeyException);
-                done();
             });
     });
 
-    test('Remove cache', (done) => {
-        return cacheService.merge(testCaches[0])
+    test('Try to update cache.', (done) => {
+        cacheService.merge(testCaches[0])
             .then((cacheId) => {
+                const cacheBeforeMerge = {...testCaches[0], _id: cacheId};
+                cacheBeforeMerge.name = 'NewUniqueName';
 
-                assert.isNotNull(cacheId);
+                return cacheService.merge(cacheBeforeMerge)
+                    .then((cacheId) => {
+                        return mongo.Cache.findById(cacheId)
+                            .then((cacheAfterMerge) => {
+                                assert.equal(cacheBeforeMerge.name, 
cacheAfterMerge.name);
+                            })
+                            .then(done);
+                    });
+            })
+            .catch(done);
+    });
 
-                return mongo.Cache.findById(cacheId)
-                    .then((cache) => {
-                        assert.isNotNull(cache);
 
-                        return cache;
-                    })
+    test('Remove cache.', (done) => {
+        cacheService.merge(testCaches[0])
+            .then((cacheId) => {
+                return mongo.Cache.findById(cacheId)
+                    .then((cache) => cache._id)
                     .then(cacheService.remove)
                     .then((results) => {
                         assert.equal(results.rowsAffected, 1);
@@ -109,13 +123,56 @@ suite('CacheService', () => {
             .catch(done);
     });
 
-    // TODO implement test
-    test('Remove all caches by user', (done) => {
-        done();
+    test('Remove null cache must be throw exception.', (done) => {
+        cacheService.merge(testCaches[0])
+            .then(()=> cacheService.remove())
+            .catch((err) => {
+                assert.instanceOf(err, errors.IllegalArgumentException);
+                done();
+            })
+    });
+
+
+    test('Remove all caches by user.', (done) => {
+        prepareUserSpaces()
+            .then(([accounts, spaces]) => {
+                const currentUser = accounts[0];
+                const userCache = {...testCaches[0], space: spaces[0][0]._id};
+
+                return cacheService.merge(userCache)
+                    .then(() => {
+                        return cacheService.removeAll(currentUser._id, false)
+                            .then(({rowsAffected})=> {
+                                assert.equal(rowsAffected, 1);
+                            })
+                    });
+            })
+            .then(done)
+            .catch(done);
     });
 
-    // TODO Implement test
-    test('Load all caches by space', (done) => {
-        done();
+    test('Load all caches by space.', (done) => {
+        prepareUserSpaces()
+            .then(([accounts, spaces]) => {
+                const currentUser = accounts[0];
+                const userCache = {...testCaches[0], space: spaces[0][0]._id};
+
+                return cacheService.merge(userCache)
+                    .then((cacheId) => {
+                        return cacheService.listByUser(currentUser._id, false)
+                            .then(({caches}) => {
+                                assert.equal(caches.length, 1);
+                                assert.equal(caches[0]._id.toString(), 
cacheId.toString());
+                            });
+                    });
+            })
+            .then(done)
+            .catch(done);
     });
+
+    // TODO
+    // test('Test link entities on merge', () => {})
+
+    // TODO
+    // test('Test link entities on remove', () => {})
 });

Reply via email to