From f1864cf94165541f3399287931f08c85a1c4b37c Mon Sep 17 00:00:00 2001 From: Frankllin Date: Sun, 24 Mar 2024 00:15:26 -0300 Subject: [PATCH] add rejection to UF search promises when an empty list is returned Prevents responses from providers that respond first, but with empty results, from being considered as the final result fix #600 --- pages/api/ibge/municipios/v1/[uf].js | 7 ++++--- services/util/rejectWhenEmptyArray.js | 13 +++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) create mode 100644 services/util/rejectWhenEmptyArray.js diff --git a/pages/api/ibge/municipios/v1/[uf].js b/pages/api/ibge/municipios/v1/[uf].js index d7afa7122..e1256d111 100644 --- a/pages/api/ibge/municipios/v1/[uf].js +++ b/pages/api/ibge/municipios/v1/[uf].js @@ -9,13 +9,14 @@ import InternalError from '@/errors/InternalError'; import BaseError from '@/errors/BaseError'; import { getCities } from '@/services/dados-abertos-br/cities'; +import { rejectWhenEmptyArray } from '@/services/util/rejectWhenEmptyArray'; const getData = async (uf, providers = null) => { const promises = []; if (!providers) { - promises.push(getContiesByUf(uf)); - promises.push(getCities(uf)); - promises.push(getStateCities(uf)); + promises.push(rejectWhenEmptyArray(getContiesByUf(uf))); + promises.push(rejectWhenEmptyArray(getCities(uf))); + promises.push(rejectWhenEmptyArray(getStateCities(uf))); } else { if (providers.includes('wikipedia')) { promises.push(getStateCities(uf)); diff --git a/services/util/rejectWhenEmptyArray.js b/services/util/rejectWhenEmptyArray.js new file mode 100644 index 000000000..bebc7bf5d --- /dev/null +++ b/services/util/rejectWhenEmptyArray.js @@ -0,0 +1,13 @@ +/** + * Rejects the promise if the data is an empty array. + * + * @param {Promise} promise + * @returns {Promise} + */ +export async function rejectWhenEmptyArray(promise) { + const data = await promise; + if (!data || data.length === 0) { + throw new Error('Empty data'); + } + return data; +}