kcg-monitoring/frontend/src/services/api.ts
htlee 0fd32081b0 refactor(frontend): 패키지 구조 리팩토링 + UI 버그 수정 (#38)
Co-authored-by: htlee <htlee@gcsc.co.kr>
Co-committed-by: htlee <htlee@gcsc.co.kr>
2026-03-18 07:41:19 +09:00

59 lines
1.6 KiB
TypeScript

import type { GeoEvent, SensorLog, ApiConfig } from '../types';
import { sampleEvents, generateSensorData } from '../data/sampleData';
const defaultConfig: ApiConfig = {
eventsEndpoint: '/api/events',
sensorEndpoint: '/api/sensors',
pollIntervalMs: 30_000,
};
let cachedSensorData: SensorLog[] | null = null;
export async function fetchEvents(_config?: Partial<ApiConfig>): Promise<GeoEvent[]> {
// In production, replace with actual API call:
// const res = await fetch(config.eventsEndpoint);
// return res.json();
return Promise.resolve(sampleEvents);
}
export async function fetchSensorData(_config?: Partial<ApiConfig>): Promise<SensorLog[]> {
// In production, replace with actual API call:
// const res = await fetch(config.sensorEndpoint);
// return res.json();
if (!cachedSensorData) {
cachedSensorData = generateSensorData();
}
return Promise.resolve(cachedSensorData);
}
export function createPollingService(
onEvents: (events: GeoEvent[]) => void,
onSensors: (data: SensorLog[]) => void,
config: Partial<ApiConfig> = {},
) {
const merged = { ...defaultConfig, ...config };
let intervalId: number | null = null;
const poll = async () => {
const [events, sensors] = await Promise.all([
fetchEvents(merged),
fetchSensorData(merged),
]);
onEvents(events);
onSensors(sensors);
};
return {
start: () => {
poll();
intervalId = window.setInterval(poll, merged.pollIntervalMs);
},
stop: () => {
if (intervalId !== null) {
clearInterval(intervalId);
intervalId = null;
}
},
};
}