Add api.js — save/load client

This commit is contained in:
otivm
2026-04-25 15:05:13 +00:00
parent 567bc08d98
commit b15f288305

37
src/api.js Normal file
View File

@@ -0,0 +1,37 @@
// Thin client for the OTIVM save API
// Backend: GET /api/save/:token — load state
// POST /api/save/:token — write state
const BASE = '/api/save'
// Generate a random 8-character hex token
export function generateToken() {
return Array.from(crypto.getRandomValues(new Uint8Array(4)))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
// Load state from server — returns parsed state object or null
export async function loadState(token) {
try {
const res = await fetch(`${BASE}/${token}`)
if (!res.ok) return null
return await res.json()
} catch {
return null
}
}
// Save state to server — returns true on success
export async function saveState(token, state) {
try {
const res = await fetch(`${BASE}/${token}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(state),
})
return res.ok
} catch {
return false
}
}