-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcloudflare.ts
More file actions
60 lines (49 loc) · 1.65 KB
/
Copy pathcloudflare.ts
File metadata and controls
60 lines (49 loc) · 1.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
import 'dotenv/config';
const CLOUDFLARE_API_URL = 'https://api.cloudflare.com/client/v4';
const CACHE_TTL = 15 * 60 * 1000; // 15 mins
const queryCache = new Map<string, { data: any; expiresAt: number }>();
export async function fetchCloudflareRadar(
endpoint: string,
params: Record<string, string> = {},
): Promise<any> {
const token = process.env.CLOUDFLARE_RADAR_TOKEN;
if (!token) {
console.warn('CLOUDFLARE_RADAR_TOKEN is not set.');
throw new Error('CLOUDFLARE_RADAR_TOKEN is missing');
}
const searchParams = new URLSearchParams(params);
searchParams.set('format', 'json');
const cacheKey = `${endpoint}?${searchParams.toString()}`;
const cached = queryCache.get(cacheKey);
if (cached && Date.now() < cached.expiresAt) {
return cached.data;
}
try {
const resp = await fetch(`${CLOUDFLARE_API_URL}${endpoint}?${searchParams.toString()}`, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
});
if (!resp.ok) {
const body = await resp.text();
throw new Error(`Cloudflare API error: ${resp.status} ${resp.statusText} - ${body}`);
}
const data = await resp.json();
if (!data.success) {
throw new Error(`Cloudflare API returned failure: ${JSON.stringify(data.errors)}`);
}
queryCache.set(cacheKey, {
data: data.result,
expiresAt: Date.now() + CACHE_TTL,
});
return data.result;
} catch (err: any) {
console.error(`Cloudflare fetch error for ${endpoint}:`, err.message);
if (cached?.data) {
console.log('Returning stale cached data as fallback.');
return cached.data;
}
throw err;
}
}