Skip to content

Instantly share code, notes, and snippets.

@DfKimera
Created April 12, 2017 18:23
Show Gist options
  • Save DfKimera/181e6a71de195a8e2ac3b31c09bca0de to your computer and use it in GitHub Desktop.
Save DfKimera/181e6a71de195a8e2ac3b31c09bca0de to your computer and use it in GitHub Desktop.
Small ES6 library to lookup addresses by CEP. Supports multiple providers and automatically swaps providers on lookup failure.
/**
* kisuma-platform
* cep_lookup.js
*
* Copyleft (c) LQDI Digital
* www.lqdi.net - 2017
* Licenced with MIT
*
* @author Aryel Tupinambá <[email protected]>
*/
import axios from "axios";
export default {
providers: {
'viacep': {
uri: (cep) => ('http://viacep.com.br/ws/' + cep + '/json/'),
mapper: (response) => {
return {
address: response.logradouro,
neighborhood: response.bairro,
city: response.localidade,
uf: response.uf,
}
}
},
'postmon': {
uri: (cep) => ('http://api.postmon.com.br/v1/cep/' + cep),
mapper: (response) => {
return {
address: response.logradouro,
neighborhood: response.bairro,
city: response.cidade,
uf: response.estado,
}
}
}
},
priority: ['viacep', 'postmon'],
lookup: function (cep, providerIndex = 0) {
let provider = this.providers[this.priority[providerIndex]];
return this.fetch(provider, cep, (res) => {
if(providerIndex >= this.priority.length) throw res;
return this.lookup(cep, ++providerIndex);
})
},
fetch: function (provider, cep, onFailure) {
return axios
.get(provider.uri(cep))
.then((response) => provider.mapper(response.data), onFailure);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment