uploadTaskMixin.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import db from "../plugins/db";
  2. import { toUploadImg } from "../plugins/imageUpload";
  3. import usePQueue from "../plugins/pQueue";
  4. /**
  5. * 上传流程:
  6. * 1、先取数据库中所有未上传的记录,生成上传任务列表,开启当前上传周期。
  7. * 2、当前上传周期内上传失败的图片进入下次上传周期。
  8. * 3、当前上传周期结束之后,定时开启下次上传周期。
  9. */
  10. export default {
  11. data() {
  12. return {
  13. uploadTask: null,
  14. taskSetTs: [],
  15. stopQueue: null,
  16. };
  17. },
  18. methods: {
  19. async addUploadTask(task) {
  20. await db.saveUploadInfo(task).catch((err) => {
  21. console.log(err);
  22. });
  23. },
  24. async initUploadTask() {
  25. this.clearTaskSetTs();
  26. const unuploadList = await db.searchUploadList({
  27. isUpload: 0,
  28. });
  29. if (!unuploadList.length) {
  30. this.taskSetTs.push(
  31. setTimeout(() => {
  32. this.initUploadTask();
  33. }, 5 * 1000)
  34. );
  35. return;
  36. }
  37. const uploadTasks = unuploadList.map((item) => {
  38. return async () => {
  39. await toUploadImg(item);
  40. await db.updateUploadState(item.id);
  41. };
  42. });
  43. const { stopQueue, buildQueue } = usePQueue();
  44. this.stopQueue = stopQueue;
  45. await buildQueue(uploadTasks);
  46. this.taskSetTs.push(
  47. setTimeout(() => {
  48. this.initUploadTask();
  49. }, 1 * 1000)
  50. );
  51. },
  52. stopUpload() {
  53. this.clearTaskSetTs();
  54. this.stopQueue && this.stopQueue();
  55. this.stopQueue = null;
  56. },
  57. clearTaskSetTs() {
  58. if (!this.taskSetTs.length) return;
  59. this.taskSetTs.forEach((t) => clearTimeout(t));
  60. this.taskSetTs = [];
  61. },
  62. },
  63. };