Created
May 1, 2019 18:06
-
-
Save ivanseidel/aeda2ddf459ef4fb8cd121f16fcab3bc to your computer and use it in GitHub Desktop.
RD Station Country/State filler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(async function fillLocation() { | |
const regions = { | |
'acre': 'AC','alagoas': 'AL','amapa': 'AP','amazonas': 'AM','bahia': 'BA', | |
'ceara': 'CE','distrito federal': 'DF','espirito santo': 'ES','goias': 'GO', | |
'maranhao': 'MA','mato grosso': 'MT','mato grosso do sul': 'MS','minas gerais': | |
'MG','para': 'PA)','paraiba': 'PB','parana': 'PR','pernambuco': 'PE', | |
'piaui': 'PI','rio de janeiro': 'RJ','rio grande do norte': 'RN', | |
'rio grande do sul': 'RS','rondonia': 'RO','roraima': 'RR','santa catarina': 'SC', | |
'sao paulo': 'SP','sergipe': 'SE','tocantins': 'TO', | |
} | |
let location = null | |
try { | |
location = await (await fetch('https://extreme-ip-lookup.com/json/')).json() | |
} catch (e) { | |
return console.log('falha na requisição de location', e) | |
} | |
let regionKey = (location.region || '').toLowerCase() | |
let regionUF = regions[regionKey] | |
if (!regionUF) { | |
return console.log('UF não encontrado', {regionKey, regionUF, location}) | |
} | |
let uf = document.querySelector('#uf') | |
if (uf.value) { | |
return console.log('UF já definido') | |
} | |
uf.value = regionUF | |
let city_id = $('#city_id') | |
if (city_id.select2('data')) { | |
return console.log('Cidade já definida', city_id.select2('data')) | |
} | |
try { | |
const rdFetcherURL = 'https://cidades.rdstation.com.br/api/cidades/' | |
const response = await (await fetch(`${rdFetcherURL}?term=${encodeURIComponent(location.city)}&state_acronym=${regionUF}`)).json() | |
let cidades = response.cities | |
let cidade = cidades[0] | |
if (!cidade) { | |
return | |
} | |
city_id.select2('data', {id: cidade.name, name: cidade.name, state: regionUF}) | |
} catch (e) { | |
console.log('Falha na requisição de cidades', e) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment