guide.ts 2.4 KB

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