init
This commit is contained in:
45
src/entities/dispatcher/model/onDutyStore.ts
Normal file
45
src/entities/dispatcher/model/onDutyStore.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { makeAutoObservable, runInAction } from 'mobx';
|
||||
import { appEvents } from '@/shared/lib';
|
||||
import { fetchOnDutyDispatchers } from '../api/dispatcherApi';
|
||||
import { cachedOnDuty } from './onDutyCache';
|
||||
import type { OnDutyDispatcher } from './types';
|
||||
|
||||
const REFRESH_INTERVAL = 60_000;
|
||||
|
||||
class OnDutyStore {
|
||||
dispatchers: OnDutyDispatcher[] = cachedOnDuty();
|
||||
phrase = '';
|
||||
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
constructor() {
|
||||
makeAutoObservable(this, {}, { autoBind: true });
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
void this.refresh();
|
||||
this.timer = setInterval(() => void this.refresh(), REFRESH_INTERVAL);
|
||||
appEvents.on('dispatchers-on-duty-changed', this.applyCache);
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
appEvents.off('dispatchers-on-duty-changed', this.applyCache);
|
||||
}
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
const { dispatchers, phrase } = await fetchOnDutyDispatchers();
|
||||
runInAction(() => {
|
||||
if (dispatchers.length > 0) this.dispatchers = dispatchers;
|
||||
if (phrase) this.phrase = phrase;
|
||||
});
|
||||
}
|
||||
|
||||
private applyCache(): void {
|
||||
this.dispatchers = cachedOnDuty();
|
||||
}
|
||||
}
|
||||
|
||||
export const onDutyStore = new OnDutyStore();
|
||||
Reference in New Issue
Block a user