core-zipcode-br
Version:
A Brazilian ZIP code validation and lookup library. Provides address lookup from various Brazilian CEP services and validates ZIP codes based on the Brazilian format.
86 lines (85 loc) • 3.3 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CepService = void 0;
const axios_1 = __importDefault(require("axios"));
const logger_1 = require("../utils/logger");
const VIA_CEP_URL = 'https://viacep.com.br/ws/';
const API_CEP_URL = 'https://cdn.apicep.com/file/apicep/';
const OPEN_CEP_URL = 'https://opencep.com/v1/';
const BRASIL_API_URL = 'https://brasilapi.com.br/api/cep/v2/';
const CEP_REGEX = /^[0-9]{5}-?[0-9]{3}$/;
class CepService {
constructor(options = {}) {
this.options = options;
}
log(message) {
if (this.options.log)
logger_1.Logger.log(message);
}
normalizeCep(cep) {
return cep.replace(/\D/g, '');
}
async fetchAddress(url, fallbackZipCode) {
try {
const { data, status } = await axios_1.default.get(url);
if (status === 200 && !data.erro) {
return {
state: data.uf || data.estado || data.state,
city: data.localidade || data.city,
street: data.logradouro || data.address || '',
neighborhood: data.bairro || data.district || data.neighborhood || '',
zipCode: fallbackZipCode,
};
}
}
catch (error) {
this.log(`Error: ${error.message}`);
}
return null;
}
async consultViaCep(zipCode) {
this.log('Consulting ViaCEP...');
const normalizedCep = this.normalizeCep(zipCode);
return this.fetchAddress(`${VIA_CEP_URL}${normalizedCep}/json`, normalizedCep);
}
async consultApiCep(zipCode) {
this.log('Consulting ApiCEP...');
const normalizedCep = this.normalizeCep(zipCode);
const formattedCep = normalizedCep.length === 8 ? `${normalizedCep.slice(0, 5)}-${normalizedCep.slice(5)}` : normalizedCep;
return this.fetchAddress(`${API_CEP_URL}${formattedCep}.json`, normalizedCep);
}
async consultOpenCep(zipCode) {
this.log('Consulting OpenCEP...');
const normalizedCep = this.normalizeCep(zipCode);
return this.fetchAddress(`${OPEN_CEP_URL}${normalizedCep}`, normalizedCep);
}
async consultBrasilApi(zipCode) {
this.log('Consulting BrasilAPI...');
const normalizedCep = this.normalizeCep(zipCode);
return this.fetchAddress(`${BRASIL_API_URL}${normalizedCep}`, normalizedCep);
}
async searchAddressByZipCode(zipCode) {
const services = [
this.consultViaCep(zipCode),
this.consultApiCep(zipCode),
this.consultOpenCep(zipCode),
this.consultBrasilApi(zipCode),
];
for (const service of services) {
const address = await service;
if (address)
return address;
}
this.log('Error: Zip code not found.');
throw new Error('Zip code not found.');
}
verify(cep) {
const isValid = CEP_REGEX.test(cep);
this.log(`CEP validation for ${cep}: ${isValid ? 'Valid' : 'Invalid'}`);
return isValid;
}
}
exports.CepService = CepService;