feat: persist upload batches in IndexedDB
This commit is contained in:
parent
dba9e7ec3b
commit
4e15605ffd
2 changed files with 95 additions and 14 deletions
61
src/services/uploadStore.ts
Normal file
61
src/services/uploadStore.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
export interface StoredUpload {
|
||||
id: string
|
||||
projectId: string
|
||||
jobId: string
|
||||
files: File[]
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
const DB_NAME = 'danable-upload-queue'
|
||||
const DB_VERSION = 1
|
||||
const STORE = 'jobs'
|
||||
|
||||
function openDb(): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.open(DB_NAME, DB_VERSION)
|
||||
req.onupgradeneeded = () => req.result.createObjectStore(STORE, { keyPath: 'id' })
|
||||
req.onsuccess = () => resolve(req.result)
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
}
|
||||
|
||||
export async function prepareUploadStorage(bytes: number): Promise<void> {
|
||||
if (!('indexedDB' in window)) throw new Error('Trình duyệt không hỗ trợ lưu hàng đợi upload')
|
||||
const estimate = await navigator.storage?.estimate?.()
|
||||
const available = (estimate?.quota ?? 0) - (estimate?.usage ?? 0)
|
||||
if (available > 0 && bytes > available * 0.8) {
|
||||
throw new Error('Không đủ dung lượng trình duyệt để resume upload sau reload')
|
||||
}
|
||||
await navigator.storage?.persist?.()
|
||||
}
|
||||
|
||||
export async function saveUpload(job: StoredUpload): Promise<void> {
|
||||
const db = await openDb()
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const req = db.transaction(STORE, 'readwrite').objectStore(STORE).put(job)
|
||||
req.onsuccess = () => resolve()
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
db.close()
|
||||
}
|
||||
|
||||
export async function deleteUpload(id: string): Promise<void> {
|
||||
const db = await openDb()
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const req = db.transaction(STORE, 'readwrite').objectStore(STORE).delete(id)
|
||||
req.onsuccess = () => resolve()
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
db.close()
|
||||
}
|
||||
|
||||
export async function listUploads(): Promise<StoredUpload[]> {
|
||||
const db = await openDb()
|
||||
const jobs = await new Promise<StoredUpload[]>((resolve, reject) => {
|
||||
const req = db.transaction(STORE, 'readonly').objectStore(STORE).getAll()
|
||||
req.onsuccess = () => resolve(req.result as StoredUpload[])
|
||||
req.onerror = () => reject(req.error)
|
||||
})
|
||||
db.close()
|
||||
return jobs
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue