index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. const mongoose = require('mongoose');
  2. /**
  3. * parent schema for GlobalNotificationSetting model
  4. */
  5. const globalNotificationSettingSchema = new mongoose.Schema({
  6. isEnabled: { type: Boolean, required: true, default: true },
  7. triggerPath: { type: String, required: true },
  8. triggerEvents: { type: [String] },
  9. });
  10. /**
  11. * GlobalNotificationSetting Class
  12. * @class GlobalNotificationSetting
  13. */
  14. class GlobalNotificationSetting {
  15. constructor(crowi) {
  16. this.crowi = crowi;
  17. }
  18. /**
  19. * enable notification setting
  20. * @param {string} id
  21. */
  22. static async enable(id) {
  23. const setting = await this.findOne({_id: id});
  24. setting.isEnabled = true;
  25. setting.save();
  26. return setting;
  27. }
  28. /**
  29. * disable notification setting
  30. * @param {string} id
  31. */
  32. static async disable(id) {
  33. const setting = await this.findOne({_id: id});
  34. setting.isEnabled = false;
  35. setting.save();
  36. return setting;
  37. }
  38. /**
  39. * find all notification settings
  40. */
  41. static async findAll() {
  42. const settings = await this.find().sort({ triggerPath: 1 });
  43. return settings;
  44. }
  45. /**
  46. * find a list of notification settings by path and a list of events
  47. * @param {string} path
  48. * @param {string} event
  49. */
  50. static async findSettingByPathAndEvent(path, event) {
  51. const pathsToMatch = generatePathsToMatch(path);
  52. const settings = await this.find({
  53. triggerPath: {$in: pathsToMatch},
  54. triggerEvents: event,
  55. isEnabled: true
  56. })
  57. .sort({ triggerPath: 1 });
  58. return settings;
  59. }
  60. }
  61. // move this to util
  62. // remove this from models/page
  63. const cutOffLastSlash = path => {
  64. const lastSlash = path.lastIndexOf('/');
  65. return path.substr(0, lastSlash);
  66. };
  67. const generatePathsOnTree = (path, pathList) => {
  68. pathList.push(path);
  69. if (path === '') {
  70. return pathList;
  71. }
  72. const newPath = cutOffLastSlash(path);
  73. return generatePathsOnTree(newPath, pathList);
  74. };
  75. const generatePathsToMatch = (originalPath) => {
  76. const pathList = generatePathsOnTree(originalPath, []);
  77. return pathList.map(path => {
  78. if (path !== originalPath) {
  79. return path + '/*';
  80. }
  81. else {
  82. return path;
  83. }
  84. });
  85. };
  86. module.exports = {
  87. class: GlobalNotificationSetting,
  88. schema: globalNotificationSettingSchema,
  89. };