import db from "../plugins/db"; import { toUploadImg } from "../plugins/imageUpload"; import usePQueue from "../plugins/pQueue"; /** * 上传流程: * 1、先取数据库中所有未上传的记录,生成上传任务列表,开启当前上传周期。 * 2、当前上传周期内上传失败的图片进入下次上传周期。 * 3、当前上传周期结束之后,定时开启下次上传周期。 */ export default { data() { return { uploadTask: null, taskSetTs: [], stopQueue: null, }; }, methods: { async addUploadTask(task) { await db.saveUploadInfo(task).catch((err) => { console.log(err); }); }, async initUploadTask() { this.clearTaskSetTs(); const unuploadList = await db.searchUploadList({ isUpload: 0, }); if (!unuploadList.length) { this.taskSetTs.push( setTimeout(() => { this.initUploadTask(); }, 5 * 1000) ); return; } const uploadTasks = unuploadList.map((item) => { return async () => { let result = true; await toUploadImg(item).catch(() => { result = false; }); if (!result) return; await db.updateUploadState(item.id); }; }); const { stopQueue, buildQueue } = usePQueue(); this.stopQueue = stopQueue; await buildQueue(uploadTasks); this.taskSetTs.push( setTimeout(() => { this.initUploadTask(); }, 1 * 1000) ); }, stopUpload() { this.clearTaskSetTs(); this.stopQueue && this.stopQueue(); this.stopQueue = null; }, clearTaskSetTs() { if (!this.taskSetTs.length) return; this.taskSetTs.forEach((t) => clearTimeout(t)); this.taskSetTs = []; }, }, };