-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.js
41 lines (37 loc) · 1.21 KB
/
fetch.js
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
const fs = require('fs').promises
const path = require('path')
async function writeFileSyncRecursive(filename, content = '') {
await fs.mkdir(path.dirname(filename), { recursive: true })
await fs.writeFile(filename, content)
}
async function fetchExchangeRates(baseCurrency = 'USD', folderName = 'data') {
const apiEndpoint = `https://open.er-api.com/v6/latest?base=${baseCurrency}`
try {
const currentDate = new Date()
const year = String(currentDate.getFullYear())
const month = String(currentDate.getMonth() + 1).padStart(2, '0')
const day = String(currentDate.getDate()).padStart(2, '0')
const response = await fetch(apiEndpoint)
const { rates } = await response.json()
const currencyFolder = path.join(
__dirname,
folderName,
baseCurrency,
year,
month,
)
const filePath = path.join(currencyFolder, `${day}.json`)
const content = JSON.stringify(rates, null, 2)
await writeFileSyncRecursive(filePath, content)
const latestFilePath = path.join(
__dirname,
folderName,
baseCurrency,
'latest.json',
)
await writeFileSyncRecursive(latestFilePath, content)
} catch (error) {
process.exit(1)
}
}
fetchExchangeRates()