summaryrefslogtreecommitdiff
path: root/hooks/use-sync-status.ts
blob: 07cb34323d15ee05f500b2c7770adb09b818c5b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// hooks/use-sync-status.ts (수정된 버전)
import useSWR from 'swr'
import useSWRMutation from 'swr/mutation'
import { mutate } from 'swr'

// 단순한 fetcher 함수들
const fetcher = async (url: string) => {
  const response = await fetch(url)
  if (!response.ok) {
    const error = new Error(`HTTP ${response.status}`)
    ;(error as any).status = response.status
    throw error
  }
  return response.json()
}

// 동기화 상태 조회
export function useSyncStatus(contractId: number, targetSystem: string = 'SHI') {
  const key = contractId 
    ? `/api/sync/status?contractId=${contractId}&targetSystem=${targetSystem}`
    : null

  const { data, error, isLoading } = useSWR(
    key,
    fetcher,
    {
      refreshInterval: 30000, // 30초마다 갱신
      revalidateOnFocus: true,
      revalidateOnReconnect: true,
      shouldRetryOnError: false, // 에러시 자동 재시도 비활성화
      dedupingInterval: 5000, // 5초 내 중복 요청 방지
    }
  )

  const refetch = () => {
    if (key) {
      mutate(key)
    }
  }

  return {
    syncStatus: data,
    isLoading,
    error,
    refetch
  }
}

// 동기화 배치 목록 조회
export function useSyncBatches(contractId: number, targetSystem: string = 'SHI') {
  const key = contractId 
    ? `/api/sync/batches?contractId=${contractId}&targetSystem=${targetSystem}`
    : null

  const { data, error, isLoading } = useSWR(
    key,
    fetcher,
    {
      revalidateOnFocus: false,
      shouldRetryOnError: false,
    }
  )

  return {
    syncBatches: data,
    isLoading,
    error
  }
}

// 동기화 설정 조회
export function useSyncConfig(contractId: number, targetSystem: string = 'SHI') {
  const key = contractId 
    ? `/api/sync/config?contractId=${contractId}&targetSystem=${targetSystem}`
    : null

  const { data, error, isLoading } = useSWR(
    key,
    fetcher,
    {
      revalidateOnFocus: false,
      shouldRetryOnError: false,
    }
  )

  return {
    syncConfig: data,
    isLoading,
    error
  }
}

// 동기화 트리거 (뮤테이션)
export function useTriggerSync() {
  const { trigger, isMutating, error } = useSWRMutation(
    '/api/sync/trigger',
    async (url: string, { arg }: { arg: { contractId: number; targetSystem?: string } }) => {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(arg)
      })
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        const error = new Error(errorData.message || `HTTP ${response.status}`)
        ;(error as any).status = response.status
        throw error
      }
      
      return response.json()
    },
    {
      onSuccess: (data, key, config) => {
        // 관련 캐시 무효화
        const { contractId, targetSystem = 'SHI' } = config.arg
        const statusKey = `/api/sync/status?contractId=${contractId}&targetSystem=${targetSystem}`
        const batchesKey = `/api/sync/batches?contractId=${contractId}&targetSystem=${targetSystem}`
        
        mutate(statusKey)
        mutate(batchesKey)
      },
      onError: (error) => {
        console.error('Sync trigger failed:', error)
      }
    }
  )

  return {
    triggerSync: trigger,
    isLoading: isMutating,
    error
  }
}

// 동기화 설정 업데이트 (뮤테이션)
export function useUpdateSyncConfig() {
  const { trigger, isMutating, error } = useSWRMutation(
    '/api/sync/config',
    async (url: string, { arg }: { arg: any }) => {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(arg)
      })
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}))
        const error = new Error(errorData.message || `HTTP ${response.status}`)
        ;(error as any).status = response.status
        throw error
      }
      
      return response.json()
    },
    {
      onSuccess: (data, key, config) => {
        // 설정 캐시 무효화
        const { contractId, targetSystem } = config.arg
        const configKey = `/api/sync/config?contractId=${contractId}&targetSystem=${targetSystem}`
        mutate(configKey)
      },
    }
  )

  return {
    updateConfig: trigger,
    isLoading: isMutating,
    error
  }
}

// 실시간 동기화 상태 훅 (높은 갱신 빈도)
export function useRealtimeSyncStatus(contractId: number, targetSystem: string = 'SHI') {
  const key = contractId 
    ? `/api/sync/status?contractId=${contractId}&targetSystem=${targetSystem}&realtime=true`
    : null

  return useSWR(
    key,
    fetcher,
    {
      refreshInterval: 5000, // 5초마다 갱신 (실시간)
      revalidateOnFocus: true,
      revalidateOnReconnect: true,
      shouldRetryOnError: false,
    }
  )
}