@@ -4,6 +4,8 @@ import { writeFile } from "node:fs/promises";
44import { dirname , resolve } from "node:path" ;
55import { fileURLToPath } from "node:url" ;
66
7+ import { fetchWithRetry } from "../src/_internals/fetch-with-retry/fetch-with-retry.ts" ;
8+
79const scriptsDir = dirname ( fileURLToPath ( import . meta. url ) ) ;
810
911type City = {
@@ -29,36 +31,43 @@ type City = {
2931 } ;
3032} ;
3133
32- const response = await fetch ( "https://servicodados.ibge.gov.br/api/v1/localidades/municipios" ) ;
34+ const main = async ( ) => {
35+ const response = await fetchWithRetry (
36+ "https://servicodados.ibge.gov.br/api/v1/localidades/municipios" ,
37+ ) ;
38+
39+ if ( ! response . ok ) {
40+ throw new Error ( `IBGE municipalities request failed with status ${ response . status } ` ) ;
41+ }
3342
34- const json = ( await response . json ( ) ) as City [ ] ;
43+ const json = ( await response . json ( ) ) as City [ ] ;
3544
36- const cities = Object . fromEntries (
37- Object . entries (
38- json . reduce (
39- ( acc , city ) => {
40- const stateInitials = city ?. microrregiao ?. mesorregiao ?. UF ?. sigla ;
45+ const cities = Object . fromEntries (
46+ Object . entries (
47+ json . reduce (
48+ ( acc , city ) => {
49+ const stateInitials = city ?. microrregiao ?. mesorregiao ?. UF ?. sigla ;
4150
42- if ( ! stateInitials ) return acc ;
51+ if ( ! stateInitials ) return acc ;
4352
44- if ( ! acc [ stateInitials ] ) {
45- acc [ stateInitials ] = [ ] ;
46- }
53+ if ( ! acc [ stateInitials ] ) {
54+ acc [ stateInitials ] = [ ] ;
55+ }
4756
48- acc [ stateInitials ] . push ( city . nome ) ;
57+ acc [ stateInitials ] . push ( city . nome ) ;
4958
50- return acc ;
51- } ,
52- { } as Record < string , string [ ] > ,
53- ) ,
54- )
55- . sort ( ( [ a ] , [ b ] ) => a . localeCompare ( b ) )
56- . map ( ( [ state , cityNames ] ) => [ state , cityNames . sort ( ( a , b ) => a . localeCompare ( b ) ) ] ) ,
57- ) ;
59+ return acc ;
60+ } ,
61+ { } as Record < string , string [ ] > ,
62+ ) ,
63+ )
64+ . sort ( ( [ a ] , [ b ] ) => a . localeCompare ( b ) )
65+ . map ( ( [ state , cityNames ] ) => [ state , cityNames . sort ( ( a , b ) => a . localeCompare ( b ) ) ] ) ,
66+ ) ;
5867
59- await writeFile (
60- resolve ( scriptsDir , ".." , "./src/_internals/constants/cities.ts" ) ,
61- `/**
68+ await writeFile (
69+ resolve ( scriptsDir , ".." , "./src/_internals/constants/cities.ts" ) ,
70+ `/**
6271 * A collection of Brazilian cities categorized by their respective states.
6372 *
6473 * @constant
@@ -82,4 +91,10 @@ await writeFile(
8291 * @property {string[]} MA - Cities in the state of Maranhão.
8392 */
8493export const DATA = ${ JSON . stringify ( cities ) } as const` ,
85- ) ;
94+ ) ;
95+ } ;
96+
97+ await main ( ) . catch ( ( error ) => {
98+ console . error ( error instanceof Error ? error . message : error ) ;
99+ process . exit ( 1 ) ;
100+ } ) ;
0 commit comments