storage.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const Model = require('objection').Model
  2. const autoload = require('auto-load')
  3. const path = require('path')
  4. const _ = require('lodash')
  5. const commonHelper = require('../../helpers/common')
  6. /* global WIKI */
  7. /**
  8. * Storage model
  9. */
  10. module.exports = class Storage extends Model {
  11. static get tableName() { return 'storage' }
  12. static get jsonSchema () {
  13. return {
  14. type: 'object',
  15. required: ['key', 'title', 'isEnabled'],
  16. properties: {
  17. id: {type: 'integer'},
  18. key: {type: 'string'},
  19. title: {type: 'string'},
  20. isEnabled: {type: 'boolean'},
  21. mode: {type: 'string'},
  22. config: {type: 'object'}
  23. }
  24. }
  25. }
  26. static async getTargets() {
  27. return WIKI.db.storage.query()
  28. }
  29. static async refreshTargetsFromDisk() {
  30. try {
  31. const dbTargets = await WIKI.db.storage.query()
  32. const diskTargets = autoload(path.join(WIKI.SERVERPATH, 'modules/storage'))
  33. let newTargets = []
  34. _.forOwn(diskTargets, (target, targetKey) => {
  35. if (!_.some(dbTargets, ['key', target.key])) {
  36. newTargets.push({
  37. key: target.key,
  38. title: target.title,
  39. isEnabled: false,
  40. mode: 'push',
  41. config: _.transform(target.props, (result, value, key) => {
  42. if (_.isPlainObject(value)) {
  43. let cfgValue = {
  44. type: typeof value.type(),
  45. value: !_.isNil(value.default) ? value.default : commonHelper.getTypeDefaultValue(value)
  46. }
  47. if (_.isArray(value.enum)) {
  48. cfgValue.enum = value.enum
  49. }
  50. _.set(result, key, cfgValue)
  51. } else {
  52. _.set(result, key, {
  53. type: typeof value(),
  54. value: commonHelper.getTypeDefaultValue(value)
  55. })
  56. }
  57. return result
  58. }, {})
  59. })
  60. }
  61. })
  62. if (newTargets.length > 0) {
  63. await WIKI.db.storage.query().insert(newTargets)
  64. WIKI.logger.info(`Loaded ${newTargets.length} new storage targets: [ OK ]`)
  65. } else {
  66. WIKI.logger.info(`No new storage targets found: [ SKIPPED ]`)
  67. }
  68. } catch (err) {
  69. WIKI.logger.error(`Failed to scan or load new storage providers: [ FAILED ]`)
  70. WIKI.logger.error(err)
  71. }
  72. }
  73. }