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