all files / src/ Fetcher.js

96.97% Statements 32/33
83.33% Branches 5/6
100% Functions 3/3
96.97% Lines 32/33
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                                                         
'use strict';
 
var log = require('./Log.js').Logger('libZotero:Fetcher');
 
var Fetcher = function(config={}){
	let defaultConfig = {
		start: 0,
		limit: 25
	};
	
	this.config = Z.extend({}, defaultConfig, config);
	this.hasMore = true;
 
	this.results = [];
	this.totalResults = null;
	this.resultInfo = {};
};
 
Fetcher.prototype.next = function(){
	Iif(this.hasMore == false){
		return Promise.resolve(null);
	}
	
	let urlconfig = Z.extend({}, this.config);
	let p = Zotero.net.queueRequest({url:urlconfig});
	p.then((response)=>{
		if(response.parsedLinks.hasOwnProperty('next')){
			this.hasMore = true;
		} else {
			this.hasMore = false;
		}
 
		this.results = this.results.concat(response.data);
		this.totalResults = response.totalResults;
		
		return response;
	});
 
	let nconfig = Z.extend({}, urlconfig);
	nconfig.start = nconfig.start + nconfig.limit;
	this.config = nconfig;
	return p;
};
 
Fetcher.prototype.fetchAll = function(){
	let results = [];
	let tryNext = () => {
		if(this.hasMore){
			return this.next().then((response)=>{
				results = results.concat(response.data);
			}).then(tryNext);
		} else {
			return Promise.resolve(results);
		}
	};
 
	return tryNext();
};
 
module.exports = Fetcher;