Skip to content

Commit

Permalink
add rejection to UF search promises when an empty list is returned
Browse files Browse the repository at this point in the history
Prevents responses from providers that respond first, but with empty results, from being considered as the final result
fix BrasilAPI#600
  • Loading branch information
frankllin15 committed Mar 24, 2024
1 parent 324fcfd commit f1864cf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
7 changes: 4 additions & 3 deletions pages/api/ibge/municipios/v1/[uf].js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
13 changes: 13 additions & 0 deletions services/util/rejectWhenEmptyArray.js
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit f1864cf

Please sign in to comment.