46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
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();
|