UNPKG

@stackbit/cms-contentful

Version:

Stackbit Contentful CMS Interface

73 lines (65 loc) 2.32 kB
export interface LazyPollerOptions<T> { notificationCallback: T; sleepTimeoutMs?: number; pollingIntervalMs?: number; logger: any; } export abstract class LazyPoller<T> { protected notificationCallback: T; private readonly sleepTimeoutMs: number; private readonly pollingIntervalMs: number; private sleepTimeout: null | ReturnType<typeof setTimeout>; private pollTimeout: null | ReturnType<typeof setTimeout>; private isSleeping: boolean; private logger: any; protected constructor({ notificationCallback, sleepTimeoutMs = 30 * 60 * 1000, pollingIntervalMs = 1000, logger }: LazyPollerOptions<T>) { this.notificationCallback = notificationCallback; this.sleepTimeoutMs = sleepTimeoutMs; this.pollingIntervalMs = pollingIntervalMs; this.logger = logger; this.sleepTimeout = null; this.pollTimeout = null; this.isSleeping = true; this.sleep = this.sleep.bind(this); this.callPoll = this.callPoll.bind(this); } resetSleepTimer() { if (this.sleepTimeout) { clearTimeout(this.sleepTimeout); } this.sleepTimeout = setTimeout(this.sleep, this.sleepTimeoutMs); if (this.isSleeping) { this.logger.debug('start polling'); this.isSleeping = false; this.setPollTimeout(); } } sleep() { this.logger.debug('sleep'); if (this.sleepTimeout) { clearTimeout(this.sleepTimeout); this.sleepTimeout = null; } this.isSleeping = true; if (this.pollTimeout) { clearTimeout(this.pollTimeout); this.pollTimeout = null; } } private setPollTimeout() { this.pollTimeout = setTimeout(this.callPoll, this.pollingIntervalMs); } private async callPoll() { this.pollTimeout = null; return Promise.resolve(this.poll(this.notificationCallback)) .catch((error) => { this.logger.error('error in pollCallback', { error: error.message }); }) .finally(() => { if (!this.isSleeping) { this.setPollTimeout(); } }); } protected abstract poll(notificationCallback: T): any; }