easyplace
Version:
API to search for ceps, streets, neighborhoods and other places
78 lines (67 loc) • 1.91 kB
JavaScript
import Place from "./models/Place";
import axios from "axios";
class EasyPlace {
constructor() {
this.names = [];
this.city = "";
this.state = "";
this.neighborhood = "";
}
async getAddressOfCep(cep) {
try {
const response = await axios.get(`https://viacep.com.br/ws/${cep}/json/`);
const data = response.data;
if(data.erro)
throw new Error("Invalid CEP value.");
return new Place(data.cep, data.logradouro,
data.complemento, data.bairro,
data.localidade, data.uf);
} catch (e) {
throw e;
}
}
searchStreetWithName(names) {
this.names = names;
return this;
}
inCity(city) {
this.city = city;
return this;
}
inState(state) {
this.state = state;
return this;
}
async search() {
try {
const response = await axios.get(this.getUrlSearch());
return this.getSearchReponse(response.data);
} catch (e) {
throw e;
}
}
inNeighborhood(neighborhood) {
this.neighborhood = neighborhood;
return this;
}
getSearchReponse(requestResponse) {
let rightResponse;
if(this.neighborhood === "")
rightResponse = requestResponse;
else {
rightResponse = requestResponse.filter((street) => {
if(street.bairro == this.neighborhood)
return street;
});
}
this.neighborhood ="";
this.city = "";
this.state = "";
this.names = [];
return rightResponse;
}
getUrlSearch() {
return `https://viacep.com.br/ws/${this.state}/${this.city}/${this.names.join(" ")}/json/`;
}
}
export default EasyPlace;