Skip to content

Commit

Permalink
fix: guard against simultaneous data fetches
Browse files Browse the repository at this point in the history
  • Loading branch information
rhyslbw committed Jan 12, 2021
1 parent a69c0ae commit 93e198f
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions packages/util/src/data_fetching/DataFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,30 @@ import { dummyLogger, Logger } from 'ts-log'

export class DataFetcher<DataValue> {
private pollingQueryTimer: SetIntervalAsyncTimer
private fetch: () => Promise<void>
private isFetching: boolean
public value: DataValue

constructor (
public name: string,
private fetchFn: FetchFunction<DataValue>,
fetchFn: FetchFunction<DataValue>,
private pollingInterval: number,
private logger: Logger = dummyLogger
) {}
) {
this.isFetching = false
this.fetch = async () => {
if (this.isFetching) return
this.isFetching = true
this.value = await fetchFn()
this.isFetching = false
}
}

public async initialize () {
this.value = await this.fetchFn()
await this.fetch()
this.logger.debug('initial value fetched', { module: 'DataFetcher', instance: this.name, value: this.value })
this.pollingQueryTimer = setIntervalAsync(async () => {
this.value = await this.fetchFn()
await this.fetch()
this.logger.debug(`value fetched after ${this.pollingInterval / 1000} seconds`, { module: 'DataFetcher', instance: this.name, value: this.value })
}, this.pollingInterval)
}
Expand Down

0 comments on commit 93e198f

Please sign in to comment.