2
0

storage.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const fs = require('fs-extra')
  2. const path = require('path')
  3. /**
  4. * Get file extension based on content type
  5. */
  6. const getFileExtension = (contentType) => {
  7. switch (contentType) {
  8. case 'markdown':
  9. return 'md'
  10. case 'html':
  11. return 'html'
  12. default:
  13. return 'txt'
  14. }
  15. }
  16. /**
  17. * Inject page metadata into contents
  18. */
  19. const injectMetadata = (page) => {
  20. let meta = [
  21. ['title', page.title],
  22. ['description', page.description]
  23. ]
  24. let metaFormatted = ''
  25. switch (page.contentType) {
  26. case 'markdown':
  27. metaFormatted = meta.map(mt => `[//]: # ${mt[0]}: ${mt[1]}`).join('\n')
  28. break
  29. case 'html':
  30. metaFormatted = meta.map(mt => `<!-- ${mt[0]}: ${mt[1]} -->`).join('\n')
  31. break
  32. default:
  33. metaFormatted = meta.map(mt => `#WIKI ${mt[0]}: ${mt[1]}`).join('\n')
  34. break
  35. }
  36. return `${metaFormatted}\n\n${page.content}`
  37. }
  38. module.exports = {
  39. async activated() {
  40. // not used
  41. },
  42. async deactivated() {
  43. // not used
  44. },
  45. async init() {
  46. await fs.ensureDir(this.config.path)
  47. },
  48. async created() {
  49. const filePath = path.join(this.config.path, `${this.page.path}.${getFileExtension(this.page.contentType)}`)
  50. await fs.outputFile(filePath, injectMetadata(this.page), 'utf8')
  51. },
  52. async updated() {
  53. const filePath = path.join(this.config.path, `${this.page.path}.${getFileExtension(this.page.contentType)}`)
  54. await fs.outputFile(filePath, injectMetadata(this.page), 'utf8')
  55. },
  56. async deleted() {
  57. const filePath = path.join(this.config.path, `${this.page.path}.${getFileExtension(this.page.contentType)}`)
  58. await fs.unlink(filePath)
  59. },
  60. async renamed() {
  61. const sourceFilePath = path.join(this.config.path, `${this.page.sourcePath}.${getFileExtension(this.page.contentType)}`)
  62. const destinationFilePath = path.join(this.config.path, `${this.page.destinationPath}.${getFileExtension(this.page.contentType)}`)
  63. await fs.move(sourceFilePath, destinationFilePath, { overwrite: true })
  64. }
  65. }