all files / src/topics/ popular.js

27.27% Statements 6/22
0% Branches 0/8
7.69% Functions 1/13
27.27% Lines 6/22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                                                                             
 
'use strict';
 
var async = require('async');
var privileges = require('../privileges');
 
module.exports = function(Topics) {
 
	Topics.getPopular = function(term, uid, count, callback) {
		count = parseInt(count, 10) || 20;
 
		if (term === 'alltime') {
			return getAllTimePopular(uid, count, callback);
		}
 
		async.waterfall([
			function(next) {
				Topics.getLatestTidsFromSet('topics:tid', 0, -1, term, next);
			},
			function(tids, next) {
				getTopics(tids, uid, count, next);
			}
		], callback);
	};
 
	function getAllTimePopular(uid, count, callback) {
		Topics.getTopicsFromSet('topics:posts', uid, 0, count - 1, function(err, data) {
			callback(err, data ? data.topics : null);
		});
	}
 
	function getTopics(tids, uid, count, callback) {
		async.waterfall([
			function(next) {
				Topics.getTopicsFields(tids, ['tid', 'postcount', 'deleted'], next);
			},
			function(topics, next) {
				tids = topics.filter(function(topic) {
					return topic && parseInt(topic.deleted, 10) !== 1;
				}).sort(function(a, b) {
					return b.postcount - a.postcount;
				}).slice(0, count).map(function(topic) {
					return topic.tid;
				});
				privileges.topics.filterTids('read', tids, uid, next);
			},
			function(tids, next) {
				Topics.getTopicsByTids(tids, uid, next);
			}
		], callback);
	}
};