guide.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. ...guide
  35. })
  36. let bcGuides: Guides = []
  37. export const getBackupGuides = () => bcGuides
  38. export const backupGuides = () => {
  39. bcGuides = guides.value.map(guide => ({...guide }))
  40. }
  41. export const transformGuide = async (guide: Guide): Promise<SGuide> => {
  42. const guideCover = await uploadFile(guide.cover)
  43. return { ...guide, cover: guideCover }
  44. }
  45. export const addGuide = addStoreItem(guides, async (guide) => {
  46. const paths = getGuidePaths(guide)
  47. const newGuide = await postAddGuide(guide)
  48. paths.forEach(path => path.guideId = newGuide.id)
  49. return newGuide
  50. }, transformGuide)
  51. export const deleteGuide = deleteStoreItem(guides, async guide => {
  52. const paths = getGuidePaths(guide)
  53. await postDeleteGuide(guide.id)
  54. guidePaths.value = guidePaths.value.filter(path => !paths.includes(path))
  55. })
  56. export const initialGuides = async () => {
  57. guides.value = await fetchGuides()
  58. await Promise.all(guides.value.map(initialGuidePathsByGuide))
  59. backupGuides()
  60. }
  61. export const recoverGuides = recoverStoreItems(guides, getBackupGuides)
  62. export const updateGuide = updateStoreItem(guides, postUpdateGuide, transformGuide)
  63. export const saveGuides = saveStoreItems(
  64. guides,
  65. getBackupGuides,
  66. {
  67. add: addGuide,
  68. update: updateGuide,
  69. delete: deleteGuide,
  70. }
  71. )
  72. export const autoSaveGuides = autoSetModeCallback([guides, guidePaths], {
  73. backup: togetherCallback([backupGuides, backupGuidePaths]),
  74. recovery: togetherCallback([recoverGuides, recoverGuidePaths]),
  75. save: async () => {
  76. await saveGuides()
  77. await saveGuidePaths()
  78. },
  79. })