guide.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { ref } from 'vue'
  2. import { autoSetModeCallback, createTemploraryID } from './sys'
  3. import {
  4. fetchGuides,
  5. postAddGuide,
  6. postDeleteGuide,
  7. postUpdateGuide,
  8. uploadFile,
  9. } from '@/api'
  10. import {
  11. togetherCallback,
  12. deleteStoreItem,
  13. addStoreItem,
  14. updateStoreItem,
  15. saveStoreItems,
  16. recoverStoreItems
  17. } from '@/utils'
  18. import {
  19. getGuidePaths,
  20. guidePaths,
  21. recoverGuidePaths,
  22. backupGuidePaths,
  23. saveGuidePaths,
  24. initialGuidePathsByGuide
  25. } from './guide-path'
  26. import type { Guide as SGuide } from '@/api'
  27. export type Guide = LocalMode<SGuide, 'cover'>
  28. export type Guides = Guide[]
  29. export const guides = ref<Guides>([])
  30. export const createGuide = (guide: Partial<Guide> = {}): Guide => ({
  31. id: createTemploraryID(),
  32. title: `路径${guides.value.length + 1}`,
  33. cover: '',
  34. showMeasure: true,
  35. showTagging: true,
  36. showPath: true,
  37. showVideo: true,
  38. ...guide
  39. })
  40. let bcGuides: Guides = []
  41. export const getBackupGuides = () => bcGuides
  42. export const backupGuides = () => {
  43. bcGuides = guides.value.map(guide => ({...guide }))
  44. }
  45. export const transformGuide = async (guide: Guide): Promise<SGuide> => {
  46. const guideCover = await uploadFile(guide.cover)
  47. return { ...guide, cover: guideCover }
  48. }
  49. export const addGuide = addStoreItem(guides, async (guide) => {
  50. const paths = getGuidePaths(guide)
  51. const newGuide = await postAddGuide(guide)
  52. paths.forEach(path => path.guideId = newGuide.id)
  53. return newGuide
  54. }, transformGuide)
  55. export const deleteGuide = deleteStoreItem(guides, async guide => {
  56. const paths = getGuidePaths(guide)
  57. await postDeleteGuide(guide.id)
  58. guidePaths.value = guidePaths.value.filter(path => !paths.includes(path))
  59. })
  60. export const initialGuides = async () => {
  61. guides.value = await fetchGuides()
  62. await Promise.all(guides.value.map(initialGuidePathsByGuide))
  63. backupGuides()
  64. }
  65. export const recoverGuides = recoverStoreItems(guides, getBackupGuides)
  66. export const updateGuide = updateStoreItem(guides, postUpdateGuide, transformGuide)
  67. export const saveGuides = saveStoreItems(
  68. guides,
  69. getBackupGuides,
  70. {
  71. add: addGuide,
  72. update: updateGuide,
  73. delete: deleteGuide,
  74. }
  75. )
  76. export const autoSaveGuides = autoSetModeCallback([guides, guidePaths], {
  77. backup: togetherCallback([backupGuides, backupGuidePaths]),
  78. recovery: togetherCallback([recoverGuides, recoverGuidePaths]),
  79. save: async () => {
  80. await saveGuides()
  81. await saveGuidePaths()
  82. },
  83. })