MCPcopy Create free account
hub / github.com/BrasilAPI/BrasilAPI / getStateCities

Function getStateCities

services/ibge/wikipedia.js:33–77  ·  view source on GitHub ↗
(uf)

Source from the content-addressed store, hash-verified

31};
32
33export const getStateCities = async (uf) => {
34 const formattedUF = uf.toUpperCase();
35 const state = CODIGOS_ESTADOS[formattedUF];
36
37 const formatName = (name) =>
38 name
39 .replace(`BR-${formattedUF}-`, '')
40 .replace(/\W-/g, '')
41 .replace('{{', '')
42 .replace('}}', '');
43
44 const formatIbgeCode = (code) =>
45 code.replace(/\W/g, '').replace('formatnum', '');
46
47 const pageNames = await wiki({
48 apiUrl: 'https://pt.wikipedia.org/w/api.php',
49 }).search(`Lista de municípios de ${state}`);
50
51 const correctIndex = pageNames.results[0].includes('por população') ? 1 : 0;
52
53 const stateInfo = await wiki({
54 apiUrl: 'https://pt.wikipedia.org/w/api.php',
55 }).page(pageNames.results[correctIndex]);
56
57 stateInfo.cities = await stateInfo.tables();
58
59 if (!stateInfo.cities || stateInfo.cities.length === 0) {
60 return [];
61 }
62
63 return stateInfo.cities[0]
64 .filter((city) => {
65 const keys = Object.keys(city).map((key) => key.toLocaleLowerCase());
66 const ibgeCodeIndex = keys.findIndex((key) => key.includes('ibge'));
67 return ibgeCodeIndex !== -1 && Object.values(city)[ibgeCodeIndex];
68 })
69 .map((city) => {
70 const keys = Object.keys(city).map((key) => key.toLocaleLowerCase());
71 const ibgeCodeIndex = keys.findIndex((key) => key.includes('ibge'));
72 const ibgeCode = Object.values(city)[ibgeCodeIndex];
73 const name = city['municípiosDoBrasil'];
74
75 return { nome: formatName(name), codigo_ibge: formatIbgeCode(ibgeCode) };
76 });
77};

Callers 1

getDataFunction · 0.90

Calls 2

formatNameFunction · 0.85
formatIbgeCodeFunction · 0.85

Tested by

no test coverage detected