storage.js 1.96 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
const fs = require('fs-extra')
const path = require('path')

/**
 * Get file extension based on content type
 */
const getFileExtension = (contentType) => {
  switch (contentType) {
    case 'markdown':
      return 'md'
    case 'html':
      return 'html'
    default:
      return 'txt'
  }
}

/**
 * Inject page metadata into contents
 */
const injectMetadata = (page) => {
  let meta = [
    ['title', page.title],
    ['description', page.description]
  ]
  let metaFormatted = ''
  switch (page.contentType) {
    case 'markdown':
      metaFormatted = meta.map(mt => `[//]: # ${mt[0]}: ${mt[1]}`).join('\n')
      break
    case 'html':
      metaFormatted = meta.map(mt => `<!-- ${mt[0]}: ${mt[1]} -->`).join('\n')
      break
    default:
      metaFormatted = meta.map(mt => `#WIKI ${mt[0]}: ${mt[1]}`).join('\n')
      break
  }
  return `${metaFormatted}\n\n${page.content}`
}

41
module.exports = {
42
  async activated() {
43
    // not used
44
  },
45
  async deactivated() {
46
    // not used
47
  },
48
  async init() {
49
    await fs.ensureDir(this.config.path)
50
  },
51
  async created() {
52 53
    const filePath = path.join(this.config.path, `${this.page.path}.${getFileExtension(this.page.contentType)}`)
    await fs.outputFile(filePath, injectMetadata(this.page), 'utf8')
54
  },
55
  async updated() {
56 57
    const filePath = path.join(this.config.path, `${this.page.path}.${getFileExtension(this.page.contentType)}`)
    await fs.outputFile(filePath, injectMetadata(this.page), 'utf8')
58
  },
59
  async deleted() {
60 61
    const filePath = path.join(this.config.path, `${this.page.path}.${getFileExtension(this.page.contentType)}`)
    await fs.unlink(filePath)
62
  },
63
  async renamed() {
64 65 66
    const sourceFilePath = path.join(this.config.path, `${this.page.sourcePath}.${getFileExtension(this.page.contentType)}`)
    const destinationFilePath = path.join(this.config.path, `${this.page.destinationPath}.${getFileExtension(this.page.contentType)}`)
    await fs.move(sourceFilePath, destinationFilePath, { overwrite: true })
67 68
  }
}