all files / src/topics/ suggested.js

21.43% Statements 6/28
0% Branches 0/8
5.88% Functions 1/17
21.43% Lines 6/28
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                                                                                                                                       
 
'use strict';
 
var async = require('async'),
	_ = require('underscore'),
 
	categories = require('../categories'),
	search = require('../search'),
	db = require('../database');
 
 
module.exports = function(Topics) {
 
	Topics.getSuggestedTopics = function(tid, uid, start, stop, callback) {
		async.parallel({
			tagTids: function(next) {
				getTidsWithSameTags(tid, next);
			},
			searchTids: function(next) {
				getSearchTids(tid, next);
			},
			categoryTids: function(next) {
				getCategoryTids(tid, next);
			}
		}, function(err, results) {
			if (err) {
				return callback(err);
			}
			var tids = results.tagTids.concat(results.searchTids).concat(results.categoryTids);
			tids = tids.filter(function(_tid, index, array) {
				return parseInt(_tid, 10) !== parseInt(tid, 10) && array.indexOf(_tid) === index;
			}).slice(start, stop + 1);
 
			Topics.getTopics(tids, uid, callback);
		});
	};
 
	function getTidsWithSameTags(tid, callback) {
		async.waterfall([
			function(next) {
				Topics.getTopicTags(tid, next);
			},
			function(tags, next) {
				async.map(tags, function(tag, next) {
					Topics.getTagTids(tag, 0, -1, next);
				}, next);
			},
			function(data, next) {
				next(null, _.unique(_.flatten(data)));
			}
		], callback);
	}
 
	function getSearchTids(tid, callback) {
		async.waterfall([
			function(next) {
				Topics.getTopicField(tid, 'title', next);
			},
			function(title, next) {
				search.searchQuery('topic', title, [], [], next);
			}
		], callback);
	}
 
	function getCategoryTids(tid, callback) {
		Topics.getTopicField(tid, 'cid', function(err, cid) {
			if (err || !cid) {
				return callback(err, []);
			}
			categories.getTopicIds('cid:' + cid + ':tids', true, 0, 9, callback);
		});
	}
 
};