forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseApiQuery.ts
More file actions
189 lines (164 loc) · 5.65 KB
/
Copy pathuseApiQuery.ts
File metadata and controls
189 lines (164 loc) · 5.65 KB
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
import { useCallback, useEffect, useRef, useState } from 'react'
import { apiFetch, ApiError } from '../api/client'
import { WIDGET_CACHE_DEFAULTS } from '../config/widgetCache'
import { scrubPII } from '../lib/piiScrub'
// ── Cache ───────────────────────────────────────────────────────────────────
interface CacheEntry<T> {
data: T
lastUpdated: number
}
const cache = new Map<string, CacheEntry<unknown>>()
function getCacheEntry<T>(key: string): CacheEntry<T> | undefined {
return cache.get(key) as CacheEntry<T> | undefined
}
function setCacheEntry<T>(key: string, data: T): void {
cache.set(key, { data, lastUpdated: Date.now() })
}
function isCacheFresh(key: string, staleTimeMs: number): boolean {
const entry = getCacheEntry(key)
if (!entry) return false
return Date.now() - entry.lastUpdated < staleTimeMs
}
// ── Public API ──────────────────────────────────────────────────────────────
export interface UseApiQueryOptions {
/** Set `false` to skip the initial fetch. Default `true`. */
enabled?: boolean
/** Time in ms before cached data is considered stale. Default 30 000. */
staleTimeMs?: number
}
export interface UseApiQueryResult<T> {
data: T | undefined
isLoading: boolean
error: ApiError | null
/** Whether the current data came from cache (within staleTime). */
isStale: boolean
/** Force a re-fetch, bypassing stale-time checks. */
refetch: () => Promise<void>
}
/**
* Type-safe, cache-aware wrapper around `apiFetch` for GET requests.
*
* Automatically manages loading/error states, caches responses keyed by the
* API path, and serves cached data within the configured `staleTime`. An
* in-flight request is aborted when the component unmounts or when a new
* fetch supersedes it.
*
* @param path API path passed to `apiFetch` (e.g. `'/trust-score/GABC…'`).
* @param options `{ enabled, staleTimeMs }`.
*
* @example
* ```tsx
* const { data, isLoading, error } = useApiQuery<TrustScore>(
* `/trust-score/${address}`,
* )
* ```
*/
export function useApiQuery<T>(
path: string,
options: UseApiQueryOptions = {}
): UseApiQueryResult<T> {
const { enabled = true, staleTimeMs = WIDGET_CACHE_DEFAULTS.STALE_TIME_MS } = options
const [data, setData] = useState<T | undefined>(() => {
const cached = getCacheEntry<T>(path)
return cached?.data
})
const [error, setError] = useState<ApiError | null>(null)
const [isLoading, setIsLoading] = useState<boolean>(enabled)
const [isStale, setIsStale] = useState<boolean>(() => {
const cached = getCacheEntry<T>(path)
return cached !== undefined && !isCacheFresh(path, staleTimeMs)
})
const mountedRef = useRef(true)
const runIdRef = useRef(0)
const abortRef = useRef<AbortController | null>(null)
const pathRef = useRef(path)
pathRef.current = path
// Cleanup: mark unmounted, abort any in-flight request
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
abortRef.current?.abort('unmounted')
abortRef.current = null
}
}, [])
const fetch = useCallback(
async (bypassCache = false): Promise<void> => {
const currentPath = pathRef.current
// Serve from cache unless bypassed
if (!bypassCache && isCacheFresh(currentPath, staleTimeMs)) {
const cached = getCacheEntry<T>(currentPath)
if (cached) {
setData(cached.data)
setIsStale(false)
setError(null)
setIsLoading(false)
return
}
}
// Offline guard
if (typeof window !== 'undefined' && !window.navigator.onLine) {
setIsLoading(false)
return
}
// Abort any previous in-flight request for this hook
abortRef.current?.abort('superseded')
const controller = new AbortController()
abortRef.current = controller
const currentRunId = ++runIdRef.current
setIsLoading(true)
setError(null)
try {
const result = await apiFetch<T>(currentPath, {
signal: controller.signal,
})
// Keep the cache as a safe boundary: callers receive the same
// sanitized value that is stored, so PII cannot leak through the
// query hook before it reaches the cache.
const sanitized = scrubPII(result)
if (mountedRef.current && currentRunId === runIdRef.current) {
setData(sanitized)
setCacheEntry(currentPath, sanitized)
setIsStale(false)
setError(null)
}
} catch (err) {
if (controller.signal.aborted) return
if (mountedRef.current && currentRunId === runIdRef.current) {
setError(err instanceof ApiError ? err : new ApiError(0, String(err)))
}
} finally {
if (mountedRef.current && currentRunId === runIdRef.current) {
setIsLoading(false)
}
}
},
[staleTimeMs]
)
// Initial fetch
useEffect(() => {
if (enabled) {
void fetch(false)
} else {
setIsLoading(false)
}
}, [enabled, fetch])
return { data, isLoading, error, isStale, refetch: () => fetch(true) }
}
/**
* Invalidate a single cached entry so the next mount or refetch re-fetches.
*
* @example
* ```ts
* invalidateApiQuery('/trust-score/GABC…')
* ```
*/
export function invalidateApiQuery(path: string): void {
cache.delete(path)
}
/**
* Clear the entire API query cache. Useful in tests.
*/
export function clearApiQueryCache(): void {
cache.clear()
}