feat(All): 第一版项目
This commit is contained in:
52
src/client/api/latency.ts
Normal file
52
src/client/api/latency.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { LatencyResult, TEST_NODES } from '@shared/types'
|
||||
|
||||
const API_BASE = '/api'
|
||||
|
||||
export interface IpInfoResponse {
|
||||
ip: string
|
||||
}
|
||||
|
||||
export interface LatencyTestResponse {
|
||||
nodeId: string
|
||||
latency: number | null
|
||||
success: boolean
|
||||
}
|
||||
|
||||
export async function fetchUserIp(): Promise<string> {
|
||||
const res = await fetch(`${API_BASE}/ip`)
|
||||
if (!res.ok) throw new Error('Failed to fetch IP')
|
||||
const data: IpInfoResponse = await res.json()
|
||||
return data.ip
|
||||
}
|
||||
|
||||
export async function testLatency(
|
||||
targetIp: string,
|
||||
nodeId: string
|
||||
): Promise<LatencyResult> {
|
||||
const res = await fetch(`${API_BASE}/latency`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ targetIp, nodeId }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
return { nodeId, latency: null, status: 'failed' }
|
||||
}
|
||||
const data: LatencyTestResponse = await res.json()
|
||||
return {
|
||||
nodeId: data.nodeId,
|
||||
latency: data.latency,
|
||||
status: data.success ? 'success' : 'failed',
|
||||
}
|
||||
}
|
||||
|
||||
export async function testAllNodes(
|
||||
targetIp: string,
|
||||
onProgress: (result: LatencyResult) => void
|
||||
): Promise<void> {
|
||||
const promises = TEST_NODES.map(async (node) => {
|
||||
onProgress({ nodeId: node.id, latency: null, status: 'testing' })
|
||||
const result = await testLatency(targetIp, node.id)
|
||||
onProgress(result)
|
||||
})
|
||||
await Promise.all(promises)
|
||||
}
|
||||
Reference in New Issue
Block a user