Skip to content

Instantly share code, notes, and snippets.

@marcelo-ribeiro
Last active October 26, 2021 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelo-ribeiro/214122b85f5597a523c4f39440d065c3 to your computer and use it in GitHub Desktop.
Save marcelo-ribeiro/214122b85f5597a523c4f39440d065c3 to your computer and use it in GitHub Desktop.
Consulta CEP usando a Brasil API. [https://github.com/marcelo-ribeiro/brasil-api-cep-v2]
const apiURL = "https://brasilapi.com.br/api";
const endpoint = `${apiURL}/cep/v2`;
/**
* @typedef IPayload
* @type {object}
* @property {string} cep
* @property {string} state
* @property {string} city
* @property {string} neighborhood
* @property {string} street
* @property {string} service
* @property {object} location
* @property {string} location.type
* @property {object} location.coordinates
* @property {string} location.coordinates.longitude
* @property {string} location.coordinates.latitude
*/
/**
* Consulta o CEP retornando um objeto com os dados do endereço
* @async
* @function getCEP
* @param {string} cep
* @returns {Promise<IPayload>} Promise retorna objeto com os dados do endereço
*/
const getCEP = async (cep) => {
try {
if (!cep) throw new ReferenceError("CEP não definido.");
const response = await fetch(`${endpoint}/${cep}`);
const payload = await response.json();
if (!response.ok) throw new Error(payload.errors[0].message);
return payload;
} catch (error) {
throw error;
}
};
export default getCEP;
import getCEP from "./brasil-api-cep-v2.js";
const inputCEP = document.querySelector("#inputCEP");
inputCEP.addEventListener("input", async ({ target }) => {
const cep = target.value.replace(/\D/g, "");
if (cep.length < 8) return;
try {
const payload = await getCEP(cep);
console.log({ payload });
} catch (error) {
alert(error.message);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment