From 0f05ae4ac1cba3952b03397c7f1baea64260a5cd Mon Sep 17 00:00:00 2001 From: Baris Usakli Date: Thu, 11 May 2017 17:16:22 -0400 Subject: [PATCH] filterpidsbycid tests --- src/posts/category.js | 47 ++++++++++++++++++++++++------------------- test/posts.js | 28 ++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 21 deletions(-) diff --git a/src/posts/category.js b/src/posts/category.js index cb9a2566c4..6efbf1ec7d 100644 --- a/src/posts/category.js +++ b/src/posts/category.js @@ -54,31 +54,36 @@ module.exports = function (Posts) { Posts.filterPidsByCid = function (pids, cid, callback) { if (!cid) { - return callback(null, pids); + return setImmediate(callback, null, pids); } if (!Array.isArray(cid) || cid.length === 1) { - // Single cid - db.isSortedSetMembers('cid:' + parseInt(cid, 10) + ':pids', pids, function (err, isMembers) { - if (err) { - return callback(err); - } + return filterPidsBySingleCid(pids, cid, callback); + } + + async.waterfall([ + function (next) { + async.map(cid, function (cid, next) { + Posts.filterPidsByCid(pids, cid, next); + }, next); + }, + function (pidsArr, next) { + next(null, _.union.apply(_, pidsArr)); + }, + ], callback); + }; + + function filterPidsBySingleCid(pids, cid, callback) { + async.waterfall([ + function (next) { + db.isSortedSetMembers('cid:' + parseInt(cid, 10) + ':pids', pids, next); + }, + function (isMembers, next) { pids = pids.filter(function (pid, index) { return pid && isMembers[index]; }); - callback(null, pids); - }); - } else { - // Multiple cids - async.map(cid, function (cid, next) { - Posts.filterPidsByCid(pids, cid, next); - }, function (err, pidsArr) { - if (err) { - return callback(err); - } - - callback(null, _.union.apply(_, pidsArr)); - }); - } - }; + next(null, pids); + }, + ], callback); + } }; diff --git a/test/posts.js b/test/posts.js index e3a0ff1294..74172d808d 100644 --- a/test/posts.js +++ b/test/posts.js @@ -714,6 +714,34 @@ describe('Post\'s', function () { }); }); + + describe('filterPidsByCid', function () { + it('should return pids as is if cid is falsy', function (done) { + posts.filterPidsByCid([1, 2, 3], null, function (err, pids) { + assert.ifError(err); + assert.deepEqual([1, 2, 3], pids); + done(); + }); + }); + + it('should filter pids by single cid', function (done) { + posts.filterPidsByCid([postData.pid, 100, 101], cid, function (err, pids) { + assert.ifError(err); + assert.deepEqual([postData.pid], pids); + done(); + }); + }); + + it('should filter pids by multiple cids', function (done) { + posts.filterPidsByCid([postData.pid, 100, 101], [cid, 2, 3], function (err, pids) { + assert.ifError(err); + assert.deepEqual([postData.pid], pids); + done(); + }); + }); + }); + + after(function (done) { db.emptydb(done); });