const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3001'; async function main() { console.log('\n--- NAS Backend API Test ---'); console.log(`Backend: ${BACKEND_URL}\n`); console.log('[1] Health check...'); try { const res = await fetch(`${BACKEND_URL}/api/health`); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = await res.json(); console.log(` Status: ${data.status}, connections: ${data.activeConnections}, photo dir: ${data.defaultPhotoDir}\n`); } catch (err) { console.log(` Failed: ${err.message}`); console.log(' Start the backend first: cd ServerFiles && node server.js\n'); process.exit(1); } const host = process.env.NAS_HOST; const port = parseInt(process.env.NAS_PORT || '22', 10); const username = process.env.NAS_USER; const password = process.env.NAS_PASS; const folder = process.env.NAS_FOLDER || '/home/user/photos'; if (!host || !username || !password) { console.log('[2-4] Skipped — set NAS_HOST, NAS_USER, NAS_PASS to run connection tests.\n'); console.log('--- Tests complete (partial) ---\n'); return; } let connectionToken = null; console.log(`[2] SFTP connect to ${host}:${port}...`); try { const res = await fetch(`${BACKEND_URL}/api/sftp/connect`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ host, port, username, password }), }); if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`); const data = await res.json(); if (!data.success) throw new Error(data.error || 'Connect failed'); connectionToken = data.connectionToken; console.log(` Connected.\n`); } catch (err) { console.log(` Failed: ${err.message}\n`); process.exit(1); } const authHeaders = { 'Content-Type': 'application/json', Authorization: `Bearer ${connectionToken}`, }; console.log(`[3] List directory "${folder}"...`); try { const res = await fetch(`${BACKEND_URL}/api/sftp/list`, { method: 'POST', headers: authHeaders, body: JSON.stringify({ path: folder }), }); if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`); const data = await res.json(); console.log(` Found ${data.count || 0} items in ${data.path}`); (data.files || []).slice(0, 5).forEach((f, i) => { console.log(` ${i + 1}. ${f.name} ${f.isDirectory ? '(dir)' : `(${f.size} bytes)`}`); }); console.log(); } catch (err) { console.log(` Failed: ${err.message}\n`); } console.log('[4] Disconnect...'); try { const res = await fetch(`${BACKEND_URL}/api/sftp/disconnect`, { method: 'POST', headers: authHeaders, }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const data = await res.json(); console.log(` ${data.message}\n`); } catch (err) { console.log(` Failed: ${err.message}\n`); } console.log('--- Tests complete ---\n'); } main().catch((err) => { console.error('Unhandled error:', err); process.exit(1); });