-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathupdateCountryList.ts
56 lines (49 loc) · 1.62 KB
/
updateCountryList.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { writeFileSync } from 'fs'
import { join } from 'path'
import type { Country } from './src/component/types'
type RestCountry = {
name: {
common: string
official: string
nativeName: Record<
string,
{
official: 'República de Nicaragua'
common: 'Nicaragua'
}
>
}
cca2: string
idd: { root: string; suffixes: string[] }
flag: string
}
const transformCountryList = (countries: RestCountry[]): Country[] =>
countries
.map(
country =>
({
name: country.name.common,
iso2: country.cca2,
dialCode: country.idd.root + (country.idd.suffixes?.length === 1 ? country.idd.suffixes[0] : ''),
dialCodeSuffixes: (country.idd.suffixes?.length === 1 ? [] : country.idd.suffixes) || [],
flag: country.flag,
invalid: !country.idd.root,
}) satisfies Country,
)
.filter(country => !country.invalid)
const getCountryList = async () => {
const fields = ['idd', 'cca2', 'name', 'flag']
const url = new URL('https://restcountries.com/v3.1/all')
url.searchParams.append('fields', fields.join())
const countries = await fetch(url).then(res => res.json())
return transformCountryList(countries as RestCountry[])
}
const updateCountryList = async () => {
const countries = await getCountryList()
const data = [
"import type { Country } from '@/component/types'",
`export const countryInformation: Country[] = ${JSON.stringify(countries)}`,
].join('\n\n')
writeFileSync(join('src', 'component', 'data.ts'), data, { encoding: 'utf-8' })
}
updateCountryList().then(console.log).catch(console.error)