Skip to content

Instantly share code, notes, and snippets.

@ViniciusFXavier
Last active January 8, 2020 13:05
Show Gist options
  • Save ViniciusFXavier/b7f0e9744c01867a948b70db5809e9c9 to your computer and use it in GitHub Desktop.
Save ViniciusFXavier/b7f0e9744c01867a948b70db5809e9c9 to your computer and use it in GitHub Desktop.
ViaCEP API service - NodeJS
const request = require('request');
const promisifiedRequest = function (options) {
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (response) {
return resolve(response);
}
if (error) {
return reject(error);
}
});
});
};
module.exports = async (cepRawValue, proxyURL = '') => {
try {
const CEP_SIZE = 8;
const cepCleanValue = cepRawValue.toString().replace(/\D+/g, '');
if (cepCleanValue.length <= CEP_SIZE) {
const options = {
url: `${proxyURL}https://viacep.com.br/ws/${cepCleanValue}/json/`,
method: 'GET',
mode: 'cors',
gzip: true,
headers: {
'content-type': 'application/json;charset=utf-8'
}
}
const response = await promisifiedRequest(options);
if (response.body) {
const responseObject = JSON.parse(response.body);
return {
cep: responseObject.cep ? responseObject.cep.replace('-', '') : cepCleanValue,
state: responseObject.uf,
city: responseObject.localidade,
neighborhood: responseObject.bairro,
street: responseObject.logradouro,
complement: responseObject.complemento
}
}
} else {
return {
message: `Zip code must contain exactly ${CEP_SIZE} characters.`,
type: 'validation_error',
errors: [{
message: `Zip code entered is longer than ${CEP_SIZE} characters.`,
service: 'cep_validation'
}]
}
}
return null;
} catch (error) {
const serviceError = {
message: error.message,
service: 'viacep'
}
if (error.name === 'FetchError') {
serviceError.message = 'Error connecting to ViaCEP service.';
}
throw serviceError;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment