uploadTaskMixin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. let result = true;
  40. await toUploadImg(item).catch(() => {
  41. result = false;
  42. });
  43. if (!result) return;
  44. await db.updateUploadState(item.id);
  45. };
  46. });
  47. const { stopQueue, buildQueue } = usePQueue();
  48. this.stopQueue = stopQueue;
  49. await buildQueue(uploadTasks);
  50. this.taskSetTs.push(
  51. setTimeout(() => {
  52. this.initUploadTask();
  53. }, 1 * 1000)
  54. );
  55. },
  56. stopUpload() {
  57. this.clearTaskSetTs();
  58. this.stopQueue && this.stopQueue();
  59. this.stopQueue = null;
  60. },
  61. clearTaskSetTs() {
  62. if (!this.taskSetTs.length) return;
  63. this.taskSetTs.forEach((t) => clearTimeout(t));
  64. this.taskSetTs = [];
  65. },
  66. },
  67. };