139 lines
4.2 KiB
TypeScript
139 lines
4.2 KiB
TypeScript
/**
|
|
* 동기화 작업 큐 관리 유틸리티
|
|
*/
|
|
import { SyncQueueItem } from './types';
|
|
import { getNetworkStatus } from './status';
|
|
|
|
// 동기화 작업 큐 관리
|
|
const SYNC_QUEUE_KEY = 'sync_queue';
|
|
|
|
/**
|
|
* 동기화 작업을 큐에 추가
|
|
*/
|
|
export const addToSyncQueue = (operation: {
|
|
type: 'upload' | 'download' | 'delete';
|
|
entityType: 'transaction' | 'budget' | 'categoryBudget';
|
|
data: Record<string, unknown>;
|
|
timestamp?: number;
|
|
retries?: number;
|
|
}): void => {
|
|
// 타임스탬프 및 재시도 횟수 추가
|
|
const enhancedOperation = {
|
|
...operation,
|
|
timestamp: operation.timestamp || Date.now(),
|
|
retries: operation.retries || 0
|
|
};
|
|
|
|
// 로컬 스토리지에서 기존 큐 가져오기
|
|
const queueString = localStorage.getItem(SYNC_QUEUE_KEY) || '[]';
|
|
let queue: typeof enhancedOperation[] = [];
|
|
|
|
try {
|
|
queue = JSON.parse(queueString);
|
|
} catch (error) {
|
|
console.error('[네트워크] 동기화 큐 파싱 오류:', error);
|
|
queue = [];
|
|
}
|
|
|
|
// 큐에 작업 추가
|
|
queue.push(enhancedOperation);
|
|
|
|
// 큐 저장
|
|
localStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(queue));
|
|
|
|
console.log(`[네트워크] 동기화 큐에 작업 추가: ${operation.type} ${operation.entityType}`);
|
|
};
|
|
|
|
/**
|
|
* 동기화 큐 가져오기
|
|
*/
|
|
export const getSyncQueue = (): SyncQueueItem[] => {
|
|
try {
|
|
const queueString = localStorage.getItem(SYNC_QUEUE_KEY) || '[]';
|
|
return JSON.parse(queueString);
|
|
} catch (error) {
|
|
console.error('[네트워크] 동기화 큐 조회 실패:', error);
|
|
return [];
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 동기화 큐에서 항목 제거
|
|
*/
|
|
export const removeFromSyncQueue = (itemId: string): void => {
|
|
try {
|
|
const queue = getSyncQueue();
|
|
const updatedQueue = queue.filter(item => item.id !== itemId);
|
|
localStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(updatedQueue));
|
|
} catch (error) {
|
|
console.error('[네트워크] 동기화 큐 항목 제거 실패:', error);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 동기화 큐 항목 업데이트
|
|
*/
|
|
export const updateSyncQueueItem = (itemId: string, updates: Partial<SyncQueueItem>): void => {
|
|
try {
|
|
const queue = getSyncQueue();
|
|
const updatedQueue = queue.map(item =>
|
|
item.id === itemId ? { ...item, ...updates } : item
|
|
);
|
|
localStorage.setItem(SYNC_QUEUE_KEY, JSON.stringify(updatedQueue));
|
|
} catch (error) {
|
|
console.error('[네트워크] 동기화 큐 항목 업데이트 실패:', error);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* 보류 중인 동기화 작업 처리
|
|
*/
|
|
export const processPendingSyncQueue = async (): Promise<void> => {
|
|
// 현재 네트워크 상태 확인
|
|
const networkStatus = getNetworkStatus();
|
|
if (networkStatus !== 'online') {
|
|
console.log('[네트워크] 오프라인 상태에서 동기화 큐 처리 불가');
|
|
return;
|
|
}
|
|
|
|
// 큐 가져오기
|
|
const queue = getSyncQueue();
|
|
if (queue.length === 0) {
|
|
console.log('[네트워크] 처리할 동기화 작업 없음');
|
|
return;
|
|
}
|
|
|
|
console.log(`[네트워크] 동기화 큐 처리 시작 (${queue.length}개 항목)`);
|
|
|
|
// 작업 처리
|
|
for (const item of queue) {
|
|
try {
|
|
console.log(`[네트워크] 동기화 작업 처리 중: ${item.type} ${item.entityType}`);
|
|
|
|
// TODO: 실제 동기화 작업 처리 로직 구현
|
|
// 예: 서버에 데이터 업로드, 다운로드 등
|
|
|
|
// 성공 시 큐에서 제거
|
|
removeFromSyncQueue(item.id);
|
|
console.log(`[네트워크] 동기화 작업 성공: ${item.type} ${item.entityType}`);
|
|
} catch (error) {
|
|
console.error(`[네트워크] 동기화 작업 실패: ${item.type} ${item.entityType}`, error);
|
|
|
|
// 재시도 횟수 증가
|
|
const retryCount = (item.retryCount || 0) + 1;
|
|
|
|
if (retryCount <= 3) {
|
|
// 재시도 횟수가 3회 이하면 업데이트
|
|
updateSyncQueueItem(item.id, { retryCount });
|
|
console.log(`[네트워크] 동기화 작업 재시도 예정 (${retryCount}/3): ${item.type} ${item.entityType}`);
|
|
} else {
|
|
// 재시도 횟수 초과 시 제거
|
|
removeFromSyncQueue(item.id);
|
|
console.log(`[네트워크] 동기화 작업 최대 재시도 횟수 초과로 제거: ${item.type} ${item.entityType}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
console.log('[네트워크] 동기화 큐 처리 완료');
|
|
};
|