all files / src/ batch.js

65.63% Statements 21/32
48.28% Branches 14/29
62.5% Functions 5/8
65.63% Lines 21/32
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                                                                                           
 
 
'use strict';
 
var async = require('async'),
	db = require('./database'),
	utils = require('../public/src/utils');
 
(function(Batch) {
 
	var DEFAULT_BATCH_SIZE = 100;
 
	Batch.processSortedSet = function(setKey, process, options, callback) {
		Iif (typeof options === 'function') {
			callback = options;
			options = {};
		}
 
		callback = typeof callback === 'function' ? callback : function(){};
		options = options || {};
 
		Iif (typeof process !== 'function') {
			return callback(new Error('[[error:process-not-a-function]]'));
		}
 
		// use the fast path if possible
		Iif (db.processSortedSet && typeof options.doneIf !== 'function' && !utils.isNumber(options.alwaysStartAt)) {
			return db.processSortedSet(setKey, process, options.batch || DEFAULT_BATCH_SIZE, callback);
		}
 
		// custom done condition
		options.doneIf = typeof options.doneIf === 'function' ? options.doneIf : function(){};
 
		var batch = options.batch || DEFAULT_BATCH_SIZE;
		var start = 0;
		var stop = batch;
		var done = false;
 
		async.whilst(
			function() {
				return !done;
			},
			function(next) {
				db.getSortedSetRange(setKey, start, stop, function(err, ids) {
					Iif (err) {
						return next(err);
					}
					Eif (!ids.length || options.doneIf(start, stop, ids)) {
						done = true;
						return next();
					}
					process(ids, function(err) {
						if (err) {
							return next(err);
						}
						start += utils.isNumber(options.alwaysStartAt) ? options.alwaysStartAt : batch + 1;
						stop = start + batch;
						next();
					});
				});
			},
			callback
		);
	};
 
}(exports));