-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathupdate-indexes.mjs
More file actions
171 lines (152 loc) · 4.79 KB
/
Copy pathupdate-indexes.mjs
File metadata and controls
171 lines (152 loc) · 4.79 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import axios from 'axios'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
export const USER_AGENT = 'rendafixa-updater/1.0 (+https://github.com/rendafixa/rendafixa.github.io)'
export const REQUEST_TIMEOUT_MS = 15_000
export const MAX_RETRIES = 3
export const INITIAL_BACKOFF_MS = 1_000
export const URLS = {
poupanca: 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.195/dados/ultimos/1?formato=json',
cdi: 'https://api.bcb.gov.br/dados/serie/bcdata.sgs.4389/dados/ultimos/1?formato=json',
selic: 'https://www.bcb.gov.br/api/servico/sitebcb/historicotaxasjuros',
}
export const apiClient = axios.create({
timeout: REQUEST_TIMEOUT_MS,
headers: { 'User-Agent': USER_AGENT },
})
export async function fetchWithRetry(url, retries = MAX_RETRIES, backoffMs = INITIAL_BACKOFF_MS) {
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await apiClient.get(url)
}
catch (error) {
const status = error.response?.status
const isRetryable = !status || status >= 500
if (attempt < retries && isRetryable) {
console.warn(` Attempt ${attempt}/${retries} failed (${error.message}). Retrying in ${backoffMs}ms...`)
await new Promise(resolve => setTimeout(resolve, backoffMs))
backoffMs *= 2
}
else {
throw error
}
}
}
}
function sanitize(input) {
return String(input).slice(0, 200).replace(/[\n\r]/g, ' ')
}
function parseBcbSeriesValue(data, label) {
if (!Array.isArray(data) || data.length === 0) {
console.error(`[ERROR] BCB API returned no data for ${label}`)
return null
}
const first = data[0]
if (!first?.valor) {
console.error(`[ERROR] Unexpected BCB API payload shape for ${label} (missing "valor")`)
return null
}
const value = Number.parseFloat(first.valor)
if (!Number.isFinite(value)) {
console.error(`[ERROR] Invalid ${label} value (not a finite number): ${sanitize(first.valor)}`)
return null
}
return value
}
export async function fetchPoupanca() {
try {
console.log('Fetching Poupanca...')
const response = await fetchWithRetry(URLS.poupanca)
const value = parseBcbSeriesValue(response.data, 'Poupanca')
if (value !== null) {
console.log('Poupanca value fetched:', value)
}
return value
}
catch (error) {
console.error(`Error fetching Poupanca after ${MAX_RETRIES} attempts:`, error.message)
return null
}
}
export async function fetchDi() {
try {
console.log('Fetching DI...')
const response = await fetchWithRetry(URLS.cdi)
const value = parseBcbSeriesValue(response.data, 'CDI')
if (value !== null) {
console.log('DI value fetched:', value)
}
return value
}
catch (error) {
console.error(`Error fetching DI after ${MAX_RETRIES} attempts:`, error.message)
return null
}
}
export async function fetchSelic() {
try {
console.log('Fetching Selic...')
const response = await fetchWithRetry(URLS.selic)
const value = response.data?.conteudo?.[0]?.MetaSelic
if (value == null || !Number.isFinite(value)) {
console.error('[ERROR] Invalid Selic response (unexpected payload shape)')
return null
}
console.log('Selic value fetched:', value)
return value
}
catch (error) {
console.error(`Error fetching Selic after ${MAX_RETRIES} attempts:`, error.message)
return null
}
}
export async function updateIndicadores(targetPath) {
const raw = fs.readFileSync(targetPath, 'utf-8')
const indicadores = JSON.parse(raw)
const [poupancaValue, selicValue, cdiValue] = await Promise.all([
fetchPoupanca(),
fetchSelic(),
fetchDi(),
])
let updated = 0
if (poupancaValue == null) {
console.warn('Skipping update: Invalid poupanca value.')
}
else {
indicadores.poupanca.value = poupancaValue
updated++
}
if (selicValue == null) {
console.warn('Skipping update: Invalid selic value.')
}
else {
indicadores.selic.value = selicValue
updated++
}
if (cdiValue == null) {
console.warn('Skipping update: Invalid cdi value.')
}
else {
indicadores.cdi.value = cdiValue
updated++
}
if (updated === 0) {
throw new Error('All API calls failed. No values updated.')
}
fs.writeFileSync(targetPath, `${JSON.stringify(indicadores, null, 2)}\n`)
console.log(`indicadores.json updated successfully (${updated}/3 values).`)
}
// Only run when executed directly (not imported by tests)
if (process.argv[1] && path.resolve(process.argv[1]) === __filename) {
const indicadoresPath = path.join(__dirname, 'app', 'assets', 'indicadores.json')
try {
await updateIndicadores(indicadoresPath)
}
catch (error) {
console.error(`[FATAL] ${error.message}`)
process.exit(1)
}
}