api.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const API_BASE = '/api/v1/admin'
  2. export const api = {
  3. async login(username, password) {
  4. const res = await fetch(`${API_BASE}/login`, {
  5. method: 'POST',
  6. headers: { 'Content-Type': 'application/json' },
  7. body: JSON.stringify({ username, password }),
  8. })
  9. if (!res.ok) {
  10. const err = await res.json()
  11. throw new Error(err.detail || 'Login failed')
  12. }
  13. return res.json()
  14. },
  15. async uploadApp(file, onProgress) {
  16. const token = localStorage.getItem('auth_token')
  17. const formData = new FormData()
  18. formData.append('file', file)
  19. return new Promise((resolve, reject) => {
  20. const xhr = new XMLHttpRequest()
  21. xhr.open('POST', `${API_BASE}/apps/upload`)
  22. xhr.setRequestHeader('Authorization', `Bearer ${token}`)
  23. xhr.upload.onprogress = (e) => {
  24. if (e.lengthComputable && onProgress) {
  25. onProgress(Math.round((e.loaded / e.total) * 100))
  26. }
  27. }
  28. xhr.onload = () => {
  29. if (xhr.status >= 200 && xhr.status < 300) {
  30. resolve(JSON.parse(xhr.responseText))
  31. } else {
  32. try {
  33. const err = JSON.parse(xhr.responseText)
  34. reject(new Error(err.detail || 'Upload failed'))
  35. } catch {
  36. reject(new Error('Upload failed'))
  37. }
  38. }
  39. }
  40. xhr.onerror = () => reject(new Error('Network error'))
  41. xhr.send(formData)
  42. })
  43. },
  44. async getApps() {
  45. const res = await fetch('/api/v1/apps')
  46. if (!res.ok) throw new Error('Failed to fetch apps')
  47. return res.json()
  48. },
  49. }