Spaces:
Build error
Build error
File size: 1,927 Bytes
55d48a7 | 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 | import { useState, useCallback } from 'react';
import type { ConnectionTestResult } from '~/components/@settings/shared/service-integration';
interface UseConnectionTestOptions {
testEndpoint: string;
serviceName: string;
getUserIdentifier?: (data: any) => string;
}
export function useConnectionTest({ testEndpoint, serviceName, getUserIdentifier }: UseConnectionTestOptions) {
const [testResult, setTestResult] = useState<ConnectionTestResult | null>(null);
const testConnection = useCallback(async () => {
setTestResult({
status: 'testing',
message: 'Testing connection...',
});
try {
const response = await fetch(testEndpoint, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
const data = await response.json();
const userIdentifier = getUserIdentifier ? getUserIdentifier(data) : 'User';
setTestResult({
status: 'success',
message: `Connected successfully to ${serviceName} as ${userIdentifier}`,
timestamp: Date.now(),
});
} else {
const errorData = (await response.json().catch(() => ({}))) as { error?: string };
setTestResult({
status: 'error',
message: `Connection failed: ${errorData.error || `${response.status} ${response.statusText}`}`,
timestamp: Date.now(),
});
}
} catch (error) {
setTestResult({
status: 'error',
message: `Connection failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
timestamp: Date.now(),
});
}
}, [testEndpoint, serviceName, getUserIdentifier]);
const clearTestResult = useCallback(() => {
setTestResult(null);
}, []);
return {
testResult,
testConnection,
clearTestResult,
isTestingConnection: testResult?.status === 'testing',
};
}
|