Files
zellyy-finance/src/utils/sync/syncOptimizer.ts
gpt-engineer-app[bot] d216daf2f4 Refactor code based on feedback
Refactor the code based on the provided feedback.
2025-03-23 10:22:23 +00:00

100 lines
3.0 KiB
TypeScript

/**
* 동기화 최적화 유틸리티
*/
import { debounce, throttle, preventDuplicateOperation } from '../performance/debounceThrottle';
import { trySyncAllData } from '@/utils/syncUtils';
import { toast } from '@/hooks/useToast.wrapper';
// 동기화 상태 플래그
let isSyncRunning = false;
let lastSyncTime = 0;
const MIN_SYNC_INTERVAL = 30000; // 최소 동기화 간격 (30초)
/**
* 최적화된 동기화 함수 - 중복 방지, 속도 제한 적용
*/
export const optimizedSync = preventDuplicateOperation(
'sync-all-data',
async (userId: string) => {
// 이미 동기화 중이면 중단
if (isSyncRunning) {
console.log('[최적화] 이미 동기화 작업이 진행 중입니다.');
return { success: false, reason: 'already-running' };
}
// 너무 빈번한 동기화 요청 방지
const now = Date.now();
if (now - lastSyncTime < MIN_SYNC_INTERVAL) {
console.log(`[최적화] 동기화 요청이 너무 빈번합니다. ${MIN_SYNC_INTERVAL / 1000}초 후 다시 시도하세요.`);
return { success: false, reason: 'too-frequent' };
}
try {
isSyncRunning = true;
console.log('[최적화] 동기화 시작...');
// 네트워크 상태 확인
if (!navigator.onLine) {
console.log('[최적화] 오프라인 상태입니다. 동기화를 건너뜁니다.');
return { success: false, reason: 'offline' };
}
// 실제 동기화 수행
const result = await trySyncAllData(userId);
// 마지막 동기화 시간 기록
lastSyncTime = Date.now();
return result;
} catch (error) {
console.error('[최적화] 동기화 오류:', error);
// 중요 오류만 사용자에게 표시
toast({
title: "동기화 오류",
description: "데이터 동기화 중 문제가 발생했습니다. 나중에 다시 시도해주세요.",
variant: "destructive",
});
return { success: false, reason: 'error', error };
} finally {
isSyncRunning = false;
}
}
);
/**
* 디바운스된 동기화 함수 (빠르게 여러 번 호출해도 마지막 한 번만 실행)
*/
export const debouncedSync = debounce(
async (userId: string) => {
console.log('[최적화] 디바운스된 동기화 실행');
return optimizedSync(userId);
},
2000 // 2초 대기
);
/**
* 스로틀된 동기화 함수 (일정 시간 내 한 번만 실행)
*/
export const throttledSync = throttle(
async (userId: string) => {
console.log('[최적화] 스로틀된 동기화 실행');
return optimizedSync(userId);
},
10000 // 10초마다 최대 한 번
);
/**
* 자동 동기화 시도 (에러 무시)
*/
export const attemptBackgroundSync = async (userId: string) => {
try {
return await optimizedSync(userId);
} catch (error) {
console.error('[최적화] 백그라운드 동기화 오류 (무시됨):', error);
return { success: false, reason: 'background-error' };
}
};