2
0

common.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const S3 = require('aws-sdk/clients/s3')
  2. /* global WIKI */
  3. /**
  4. * Deduce the file path given the `page` object and the object's key to the page's path.
  5. */
  6. const getFilePath = (page, pathKey) => {
  7. const fileName = `${page[pathKey]}.${page.getFileExtension()}`
  8. const withLocaleCode = WIKI.config.lang.namespacing && WIKI.config.lang.code !== page.localeCode
  9. return withLocaleCode ? `${page.localeCode}/${fileName}` : fileName
  10. }
  11. /**
  12. * Can be used with S3 compatible storage.
  13. */
  14. module.exports = class S3CompatibleStorage {
  15. constructor(storageName) {
  16. this.storageName = storageName
  17. }
  18. async activated() {
  19. // not used
  20. }
  21. async deactivated() {
  22. // not used
  23. }
  24. async init() {
  25. WIKI.logger.info(`(STORAGE/${this.storageName}) Initializing...`)
  26. const { accessKeyId, secretAccessKey, region, bucket, endpoint } = this.config
  27. this.s3 = new S3({
  28. accessKeyId,
  29. secretAccessKey,
  30. region,
  31. endpoint,
  32. params: { Bucket: bucket },
  33. apiVersions: '2006-03-01'
  34. })
  35. // determine if a bucket exists and you have permission to access it
  36. await this.s3.headBucket().promise()
  37. WIKI.logger.info(`(STORAGE/${this.storageName}) Initialization completed.`)
  38. }
  39. async created(page) {
  40. WIKI.logger.info(`(STORAGE/${this.storageName}) Creating file ${page.path}...`)
  41. const filePath = getFilePath(page, 'path')
  42. await this.s3.putObject({ Key: filePath, Body: page.injectMetadata() }).promise()
  43. }
  44. async updated(page) {
  45. WIKI.logger.info(`(STORAGE/${this.storageName}) Updating file ${page.path}...`)
  46. const filePath = getFilePath(page, 'path')
  47. await this.s3.putObject({ Key: filePath, Body: page.injectMetadata() }).promise()
  48. }
  49. async deleted(page) {
  50. WIKI.logger.info(`(STORAGE/${this.storageName}) Deleting file ${page.path}...`)
  51. const filePath = getFilePath(page, 'path')
  52. await this.s3.deleteObject({ Key: filePath }).promise()
  53. }
  54. async renamed(page) {
  55. WIKI.logger.info(`(STORAGE/${this.storageName}) Renaming file ${page.sourcePath} to ${page.destinationPath}...`)
  56. const sourceFilePath = getFilePath(page, 'sourcePath')
  57. const destinationFilePath = getFilePath(page, 'destinationPath')
  58. await this.s3.copyObject({ CopySource: sourceFilePath, Key: destinationFilePath }).promise()
  59. await this.s3.deleteObject({ Key: sourceFilePath }).promise()
  60. }
  61. }