2025-11-12 11:13:39 -03:00
|
|
|
const axios = require("axios");
|
|
|
|
|
|
2025-11-14 08:16:04 -03:00
|
|
|
const getConsultaCep = async (rawCep, rawNumero) => {
|
|
|
|
|
if (!rawCep) {
|
|
|
|
|
throw new Error("cep é obrigatório");
|
|
|
|
|
}
|
2025-11-12 11:13:39 -03:00
|
|
|
const cep = String(rawCep).trim().replace(/\D/g, "");
|
2025-11-14 08:16:04 -03:00
|
|
|
if (cep.length !== 8) {
|
|
|
|
|
throw new Error("cep inválido, verifique se foram digitados apenas números");
|
|
|
|
|
}
|
2025-11-12 11:13:39 -03:00
|
|
|
const numero = rawNumero ? String(rawNumero).trim() : "";
|
|
|
|
|
try {
|
|
|
|
|
const cepRestUrl = 'https://api.cep.rest/';
|
|
|
|
|
const address = await axios.post(cepRestUrl, { cep });
|
2025-11-14 08:16:04 -03:00
|
|
|
|
2025-11-12 11:13:39 -03:00
|
|
|
if (address.data && address.data.code === 404) {
|
2025-11-14 08:16:04 -03:00
|
|
|
return null; // Controller tratará como 'Endereço não encontrado'
|
2025-11-12 11:13:39 -03:00
|
|
|
} else if (address.data && address.data.code) {
|
2025-11-14 08:16:04 -03:00
|
|
|
throw new Error("Erro ao consultar o CEP na API externa");
|
2025-11-12 11:13:39 -03:00
|
|
|
} else {
|
|
|
|
|
if (numero) address.data.numero = numero;
|
2025-11-14 08:16:04 -03:00
|
|
|
return address.data;
|
2025-11-12 11:13:39 -03:00
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error("Erro ao consultar o CEP:", error);
|
2025-11-14 08:16:04 -03:00
|
|
|
throw new Error("Erro ao consultar o CEP");
|
2025-11-12 11:13:39 -03:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
module.exports = { getConsultaCep };
|