storage.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. WIKI.logger.info('(STORAGE/DISK) Initializing...')
  47. await fs.ensureDir(this.config.path)
  48. WIKI.logger.info('(STORAGE/DISK) Initialization completed.')
  49. },
  50. async sync() {
  51. // not used
  52. },
  53. async created(page) {
  54. WIKI.logger.info(`(STORAGE/DISK) Creating file ${page.path}...`)
  55. const filePath = path.join(this.config.path, `${page.path}.${getFileExtension(page.contentType)}`)
  56. await fs.outputFile(filePath, injectMetadata(page), 'utf8')
  57. },
  58. async updated(page) {
  59. WIKI.logger.info(`(STORAGE/DISK) Updating file ${page.path}...`)
  60. const filePath = path.join(this.config.path, `${page.path}.${getFileExtension(page.contentType)}`)
  61. await fs.outputFile(filePath, injectMetadata(page), 'utf8')
  62. },
  63. async deleted(page) {
  64. WIKI.logger.info(`(STORAGE/DISK) Deleting file ${page.path}...`)
  65. const filePath = path.join(this.config.path, `${page.path}.${getFileExtension(page.contentType)}`)
  66. await fs.unlink(filePath)
  67. },
  68. async renamed(page) {
  69. WIKI.logger.info(`(STORAGE/DISK) Renaming file ${page.sourcePath} to ${page.destinationPath}...`)
  70. const sourceFilePath = path.join(this.config.path, `${page.sourcePath}.${getFileExtension(page.contentType)}`)
  71. const destinationFilePath = path.join(this.config.path, `${page.destinationPath}.${getFileExtension(page.contentType)}`)
  72. await fs.move(sourceFilePath, destinationFilePath, { overwrite: true })
  73. }
  74. }