findLikeConsumers.js 1.2 KB
// React client will ask nodejs server for the list of all consumers that match part of its name
function FindLikeConsumers(partOfConsumerName) {
  var partOfConsumerNameUppercase = partOfConsumerName.toUpperCase();
	return new Promise(function(resolve, reject) {
		fetch('consumidores').then((res) => {
			// asks node the list of all consumers
			res.json().then((allConsumers) => {
				var foundConsumers = [];
				var maximumSearchLines = 10;
				var context = { foundConsumers, maximumSearchLines, partOfConsumerNameUppercase };
				allConsumers.every(testIfContainsText, context);
				if (foundConsumers === null) {
					console.log('Não encontrou consumidores com o texto digitado.');
					reject('indefinido');
				} else {
					resolve(context.foundConsumers);
				}
			});
		});
	});
}

function testIfContainsText(element, index) {
	if (element.label.indexOf(this.partOfConsumerNameUppercase) !== -1 && this.maximumSearchLines > 0) {
		var obj = {};
		obj.label = element.label;
		obj.value = element.value;
		this.foundConsumers.push(obj);
		this.maximumSearchLines--;
		return true;
	} else {
		if (this.maximumSearchLines > 0) {
			return true;
		} else {
			return false;
		}
	}
}

export default FindLikeConsumers;