fix(cnpj): limita consultas e sinaliza indisponibilidade do provedor by lucianopf · Pull Request #923 · BrasilAPI/BrasilAPI · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions errors/ServiceUnavailableError.js
5 changes: 5 additions & 0 deletions pages/api/cnpj/v1/[cnpj].js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import app from '@/app';
import BadRequestError from '@/errors/BadRequestError';
import NotFoundError from '@/errors/NotFoundError';
import ServiceUnavailableError from '@/errors/ServiceUnavailableError';
import { getCnpjData } from '@/services/cnpj';

async function getCnpjInfo(request, response) {
try {
const result = await getCnpjData(request.query.cnpj);
return response.status(result.status).json(result.data);
} catch (error) {
if (error instanceof ServiceUnavailableError) {
response.setHeader('Cache-Control', 'no-store');
throw error;
}
if (error.response?.status === 400) {
throw new BadRequestError({ message: error.response.data.message });
}
Expand Down
15 changes: 15 additions & 0 deletions pages/docs/doc/cnpj.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,21 @@
}
}
},
"503": {
"description": "Serviço de consulta temporariamente indisponível: falha ou tempo limite de 5 segundos na API Minha Receita. A resposta não deve ser armazenada em cache.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorMessage"
},
"example": {
"name": "ServiceUnavailableError",
"message": "Serviço de consulta de CNPJ temporariamente indisponível.",
"type": "service_unavailable"
}
}
}
},
"404": {
"description": "CNPJ não encontrado na API Minha Receita.",
"content": {
Expand Down
31 changes: 29 additions & 2 deletions services/cnpj.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,31 @@
import axios from 'axios';
import ServiceUnavailableError from '@/errors/ServiceUnavailableError';

export const getCnpjData = (cnpj) =>
axios.get(`https://minhareceita.org/${cnpj}`);
const PROVIDER_TIMEOUT_MS = 5000;

export const getCnpjData = async (cnpj) => {
const controller = new AbortController();
// Bound the whole request, including connection establishment.
const deadline = setTimeout(() => controller.abort(), PROVIDER_TIMEOUT_MS);

try {
return await axios.get(`https://minhareceita.org/${cnpj}`, {
timeout: PROVIDER_TIMEOUT_MS,
signal: controller.signal,
});
} catch (error) {
const status = error.response?.status;
if (
axios.isAxiosError(error) &&
((status >= 500 && status <= 599) ||
(!error.response && (error.request || controller.signal.aborted)))
) {
throw new ServiceUnavailableError({
message: 'Serviço de consulta de CNPJ temporariamente indisponível.',
});
}
throw error;
} finally {
clearTimeout(deadline);
}
};
226 changes: 226 additions & 0 deletions tests/cnpj-contract.test.js
Loading