63 lines
2.1 KiB
TypeScript
63 lines
2.1 KiB
TypeScript
export interface StoredUpload {
|
|
id: string
|
|
projectId: string
|
|
jobId: string
|
|
files: File[]
|
|
createdAt: number
|
|
kind?: 'images' | 'zip' | 'zip-import' | 'coco' | 'yolo'
|
|
r2Key?: string
|
|
}
|
|
|
|
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
|
|
}
|