0
Convert Exchange Rates
One script reply has been approved by the moderators Verified

Convert an arbitrary amount from one currency to another.

Created by hugo697 56 days ago Viewed 14 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 56 days ago
1
type Abstractapi = {
2
	apiKey: string
3
}
4

5
export async function main(
6
	resource: Abstractapi,
7
	baseCurrency: string,
8
	targetCurrency: string,
9
	amountToConvert: number,
10
	exchangeDate?: `${number}-${number}-${number}` // YYYY-MM-DD
11
) {
12
	const queryParams = new URLSearchParams({
13
		api_key: resource.apiKey,
14
		base: baseCurrency,
15
		target: targetCurrency,
16
		base_amount: amountToConvert.toString()
17
	})
18

19
	if (exchangeDate) {
20
		queryParams.append('date', exchangeDate)
21
	}
22

23
	const endpoint = `https://exchange-rates.abstractapi.com/v1/convert?${queryParams.toString()}`
24

25
	const response = await fetch(endpoint, {
26
		method: 'GET'
27
	})
28

29
	if (!response.ok) {
30
		throw new Error(`HTTP error! status: ${response.status}`)
31
	}
32

33
	const data = await response.json()
34

35
	return data
36
}
37