Skip to content

Commit

Permalink
Merge branch 'main' into feature/dados-senado
Browse files Browse the repository at this point in the history
  • Loading branch information
LorhanSohaky committed Apr 21, 2023
2 parents c032c6a + 068843b commit 9c3dbd7
Show file tree
Hide file tree
Showing 21 changed files with 842 additions and 64 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Caso você esteja lendo esta versão de README, você está pegando o projeto nu
Veja mais detalhes sobre **Como contribuir** no arquivo [CONTRIBUTING.md](CONTRIBUTING.md)

## Termos de Uso
O BrasilAPI é uma iniciativa feita de brasileiros para brasileiros, por favor, não abuse deste serviço. Estamos em beta e ainda elaborando os Termos de Uso, mas por enquanto por favor não utilize formas automatizadas para fazer "crawling" dos dados da API. Um exemplo prático disto é um dos maiores provedores de telefonia do Brasil estar revalidando, neste exato momento, todos os Ceps (de `00000000` até `99999999`) e estourando em 5 vezes o limite atual da nossa conta no servidor. O volume de consulta dever ter a natureza de uma pessoa real requisitando um determinado dado. E para consultas com um alto volume automatizado, iremos mais para frente fornecer alguma solução, como por exemplo, conseguir fazer o download de toda a base de Ceps em uma única request.
O BrasilAPI é uma iniciativa feita de brasileiros para brasileiros, por favor, não abuse deste serviço. Estamos em beta e ainda elaborando os Termos de Uso, mas por enquanto por favor não utilize formas automatizadas para fazer "crawling" dos dados da API. Um exemplo prático disso foi quando um dos maiores provedores de telefonia do Brasil estava validando novamente todos os CEPs (de 00000000 até 99999999) e ultrapassando em cinco vezes o limite atual da nossa conta no servidor. O volume de consultas deve ter a natureza de uma pessoa real requisitando um determinado dado. Para consultas com um alto volume automatizado forneceremos posteriormente alguma solução, como, por exemplo, permitir o download de toda a base de CEPs em uma única requisição.

## Pessoas que já contribuiram

Expand All @@ -65,6 +65,10 @@ Abaixo segue uma lista de integrações com a BrasilApi fornecidas pela comunida
**.Net**
* **[BrasilAPI-DotNet](https://github.com/farukaf/BrasilAPI-DotNet)** criado por [@farukaf](https://github.com/farukaf)

**PHP**
* **[brasilapi-php](https://github.com/andreoneres/brasilapi-php)** criado por [@andreoneres](https://github.com/andreoneres)
* **[brasilapi-php](https://github.com/Corviz/brasilapi-php)** Criado por [@carloscarucce](https://github.com/carloscarucce)

**Python**
* **[brasilapy](https://github.com/lipe14-ops/brasilapy)** Criado por [@lipe14-ops](https://github.com/lipe14-ops)

Expand All @@ -77,6 +81,11 @@ Abaixo segue uma lista de integrações com a BrasilApi fornecidas pela comunida
**Delphi**
* **[BrasilAPI-Delphi](https://github.com/gabrielbaltazar/brasilapi4D)** Criado por [@GabrielBaltazar](https://github.com/gabrielbaltazar)

**V**
* **[BrasilAPI-V](https://github.com/ldedev/brasilapi-v)** Criado por [@ldedev(André)](https://github.com/ldedev)



## Autores

| [<img src="https://github.com/filipedeschamps.png?size=115" width=115><br><sub>@filipedeschamps</sub>](https://github.com/filipedeschamps) | [<img src="https://github.com/lucianopf.png?size=115" width=115><br><sub>@lucianopf</sub>](https://github.com/lucianopf) |
Expand Down
34 changes: 25 additions & 9 deletions lib/fetchGeocoordinateFromBrazilLocation.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@ function getAgent() {
return cacheAgent;
}

async function fetchGeocoordinateFromBrazilLocation({ state, city, street }) {
async function fetchGeocoordinateFromBrazilLocation({
state,
city,
street,
cep,
}) {
const agent = getAgent();
const encodedState = encodeURI(state);
const encodedCity = encodeURI(city);
const encodedStreet = encodeURI(street);

const country = 'Brasil';
const queryString = `format=json&addressdetails=1&country=${country}&state=${encodedState}&city=${encodedCity}&street=${encodedStreet}&limit=1`;
const queryString = `format=json&addressdetails=1&country=${country}&state=${encodedState}&city=${encodedCity}&street=${encodedStreet}`;

const response = await fetch(
`https://nominatim.openstreetmap.org/search/?${queryString}`,
Expand All @@ -26,15 +31,26 @@ async function fetchGeocoordinateFromBrazilLocation({ state, city, street }) {

const jsonData = await response.json();

if (jsonData.length > 0) {
const { lat: latitude, lon: longitude } = jsonData[0];
return { type: 'Point', coordinates: { longitude, latitude } };
const cleanedCep = cep.replace(/\D/g, '');
const exactLocation = jsonData.find(
(item) => item.address.postcode.replace(/\D/g, '') === cleanedCep
);
const approximateLocation = jsonData.find(
(item) =>
item.address.postcode.replace(/\D/g, '').slice(0, 5) ===
cleanedCep.slice(0, 5)
);
const location = exactLocation || approximateLocation;

if (!location) {
return {
type: 'Point',
coordinates: { longitude: undefined, latitude: undefined },
};
}

return {
type: 'Point',
coordinates: { longitude: undefined, latitude: undefined },
};
const { lat: latitude, lon: longitude } = location;
return { type: 'Point', coordinates: { longitude, latitude } };
}

export default fetchGeocoordinateFromBrazilLocation;
50 changes: 43 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
"node": ">=16 <17"
},
"dependencies": {
"adm-zip": "0.5.10",
"apollo-server-micro": "2.24.0",
"axios": "0.21.1",
"bluebird": "3.7.2",
"cep-promise": "4.3.0",
"cep-promise": "4.4.0",
"cors": "2.8.5",
"dayjs": "1.11.7",
"fast-xml-parser": "4.0.11",
"graphql": "15.5.0",
"lodash": "4.17.21",
Expand All @@ -20,6 +22,7 @@
"next": "10.2.0",
"next-connect": "0.9.1",
"next-sitemap": "1.6.168",
"papaparse": "5.4.0",
"piscina": "3.2.0",
"react": "17.0.1",
"react-dom": "17.0.1",
Expand Down
41 changes: 41 additions & 0 deletions pages/api/cvm/corretoras/v1/[cnpj].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import app from '@/app';

import BaseError from '@/errors/BaseError';
import NotFoundError from '@/errors/NotFoundError';
import InternalError from '@/errors/InternalError';

import { getExchangesData } from '../../../../../services/cvm/corretoras';

const action = async (request, response) => {
try {
const exchangeCode = request.query.cnpj.replace(/\D/gim, '');

const allExchangesData = await getExchangesData();

const exchangeData = allExchangesData.find(
({ cnpj }) => cnpj === exchangeCode
);

if (!exchangeData) {
throw new NotFoundError({
message: 'Nenhuma corretora localizada',
type: 'exchange_error',
name: 'EXCHANGE_NOT_FOUND',
});
}

response.status(200).json(exchangeData);
} catch (err) {
if (err instanceof BaseError) {
throw err;
}

throw new InternalError({
message: 'Erro ao buscar informações sobre corretora',
type: 'exchange_error',
name: 'EXCHANGE_INTERNAL',
});
}
};

export default app({ cache: 86400 }).get(action);
25 changes: 25 additions & 0 deletions pages/api/cvm/corretoras/v1/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import app from '@/app';

import BaseError from '@/errors/BaseError';

import InternalError from '@/errors/InternalError';
import { getExchangesData } from '../../../../../services/cvm/corretoras';

const action = async (request, response) => {
try {
const allExchangesData = await getExchangesData();
response.status(200).json(allExchangesData);
} catch (err) {
if (err instanceof BaseError) {
throw err;
}

throw new InternalError({
message: 'Erro ao buscar informações sobre corretora',
type: 'exchange_error',
name: 'EXCHANGE_INTERNAL',
});
}
};

export default app({ cache: 86400 }).get(action);
52 changes: 52 additions & 0 deletions pages/api/pix/v1/participants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import app from '@/app';
import BaseError from '@/errors/BaseError';
import InternalError from '@/errors/InternalError';
import { getPixParticipants, formatCsvFile } from '@/services/pix/participants';

const obtainPixParticipantList = async (actual = true) => {
try {
const response = await getPixParticipants();

return response;
} catch (error) {
if (actual && error.response.status === 404) {
return getPixParticipants(false);
}

throw new InternalError({
status: 500,
message: `Erro ao obter as informações do BCB ou informações inexistentes`,
name: 'PIX_LIST_ERROR',
type: 'PIX_LIST_ERROR',
});
}
};

const action = async (request, response) => {
try {
const pixParticipantsList = await obtainPixParticipantList();

const parsedData = formatCsvFile(pixParticipantsList);

response.status(200);
response.json(parsedData);
} catch (error) {
if (error instanceof BaseError) {
throw error;
}

throw new InternalError({
status: 500,
message: `Erro ao obter as informações do BCB`,
name: 'PIX_LIST_ERROR',
type: 'PIX_LIST_ERROR',
});
}
};

/**
* Cache de 21600s (6 horas) devido a não saber que horas os dados são gerados pelo BCB.
* Logo foi utilizado um cache longo para caso não exista as infos, utilize a do dia anterior como base, já que não é um dado que tem alta atualização
*/

export default app({ cache: 21600 }).get(action);
Loading

0 comments on commit 9c3dbd7

Please sign in to comment.