0

Current Weather

by
Published Dec 20, 2024

Current weather or realtime weather API method allows a user to get up to date current weather information

Script weatherapi Verified

The script

Submitted by hugo697 Bun
Verified 536 days ago
1
//native
2
type Weatherapi = {
3
	apiKey: string
4
}
5

6
export async function main(
7
	auth: Weatherapi,
8
	params: {
9
		q: string
10
		lang?:
11
			| 'ar'
12
			| 'bn'
13
			| 'bg'
14
			| 'zh'
15
			| 'zh_tw'
16
			| 'cs'
17
			| 'da'
18
			| 'nl'
19
			| 'fi'
20
			| 'fr'
21
			| 'de'
22
			| 'el'
23
			| 'hi'
24
			| 'hu'
25
			| 'it'
26
			| 'ja'
27
			| 'jv'
28
			| 'ko'
29
			| 'zh_cmn'
30
			| 'mr'
31
			| 'pl'
32
			| 'pt'
33
			| 'pa'
34
			| 'ro'
35
			| 'ru'
36
			| 'sr'
37
			| 'si'
38
			| 'sk'
39
			| 'es'
40
			| 'sv'
41
			| 'ta'
42
			| 'te'
43
			| 'tr'
44
			| 'uk'
45
			| 'ur'
46
			| 'vi'
47
			| 'zh_wuu'
48
			| 'zh_hsn'
49
			| 'zh_yue'
50
			| 'zu'
51
	}
52
) {
53
	const url = new URL(`http://api.weatherapi.com/v1/current.json`)
54

55
	// Append the API key for authentication
56
	url.searchParams.append('key', auth.apiKey)
57

58
	// Append the query parameters if provided
59
	for (const [key, value] of Object.entries(params)) {
60
		if (value !== undefined && value !== '') {
61
			url.searchParams.append(key, value.toString())
62
		}
63
	}
64

65
	const response = await fetch(url.toString(), {
66
		method: 'GET'
67
	})
68

69
	if (!response.ok) {
70
		const errorText = await response.text()
71
		throw new Error(
72
			`WeatherAPI request failed: ${response.status} ${response.statusText} - ${errorText}`
73
		)
74
	}
75

76
	return await response.json()
77
}
78