@@ -12,8 +12,8 @@ import {
1212import { datelog , safeParseFloat , standardizeNames } from './util'
1313
1414const nanoDb = nano ( config . couchDbFullpath )
15- const QUERY_FREQ_MS = 15000
16- const QUERY_LIMIT = 50
15+ const QUERY_FREQ_MS = 3000
16+ const QUERY_LIMIT = 10
1717const snooze : Function = async ( ms : number ) =>
1818 await new Promise ( ( resolve : Function ) => setTimeout ( resolve , ms ) )
1919
@@ -207,23 +207,41 @@ const dateRoundDownHour = (dateString: string): string => {
207207 return new Date ( date ) . toISOString ( )
208208}
209209
210+ const RETRY_DELAY = 1500
211+ const MAX_RETRIES = 5
212+
210213async function getExchangeRate (
211214 ca : string ,
212215 cb : string ,
213- date : string
216+ date : string ,
217+ retry : number = 0
214218) : Promise < number > {
215219 const hourDate = dateRoundDownHour ( date )
216220 const currencyA = standardizeNames ( ca )
217221 const currencyB = standardizeNames ( cb )
218222 const url = `https://rates2.edge.app/v1/exchangeRate?currency_pair=${ currencyA } _${ currencyB } &date=${ hourDate } `
219223 try {
220224 const result = await fetch ( url , { method : 'GET' } )
225+ if ( ! result . ok ) {
226+ if ( result . status === 429 ) {
227+ datelog ( `Rate limit hit` )
228+ }
229+ const text = await result . text ( )
230+ throw new Error ( `Rates error: ${ text } ` )
231+ }
221232 const jsonObj = await result . json ( )
222233 datelog (
223234 `Rate for ${ currencyA } -> ${ currencyB } ${ date } : ${ jsonObj . exchangeRate } `
224235 )
225236 return safeParseFloat ( jsonObj . exchangeRate )
226237 } catch ( e ) {
238+ if ( retry < MAX_RETRIES ) {
239+ const snoozeTime = Math . pow ( 2 , retry ) * RETRY_DELAY
240+
241+ datelog ( `snoozing for ${ snoozeTime } ms` )
242+ await snooze ( snoozeTime )
243+ return await getExchangeRate ( ca , cb , date , retry + 1 )
244+ }
227245 datelog (
228246 `Could not not get exchange rate for ${ currencyA } and ${ currencyB } at ${ date } .` ,
229247 e
0 commit comments