user-group.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. const debug = require('debug')('growi:models:userGroup');
  2. const mongoose = require('mongoose');
  3. const mongoosePaginate = require('mongoose-paginate-v2');
  4. /*
  5. * define schema
  6. */
  7. const ObjectId = mongoose.Schema.Types.ObjectId;
  8. const schema = new mongoose.Schema({
  9. userGroupId: String,
  10. name: { type: String, required: true, unique: true },
  11. createdAt: { type: Date, default: Date.now },
  12. parent: { type: ObjectId, ref: 'UserGroup', index: true },
  13. description: { type: String, default: '' },
  14. });
  15. schema.plugin(mongoosePaginate);
  16. class UserGroup {
  17. /**
  18. * public fields for UserGroup model
  19. *
  20. * @readonly
  21. * @static
  22. * @memberof UserGroup
  23. */
  24. static get USER_GROUP_PUBLIC_FIELDS() {
  25. return '_id name createdAt parent description';
  26. }
  27. /**
  28. * limit items num for pagination
  29. *
  30. * @readonly
  31. * @static
  32. * @memberof UserGroup
  33. */
  34. static get PAGE_ITEMS() {
  35. return 10;
  36. }
  37. /*
  38. * model static methods
  39. */
  40. // Generate image path
  41. static createUserGroupPictureFilePath(userGroup, name) {
  42. const ext = `.${name.match(/(.*)(?:\.([^.]+$))/)[2]}`;
  43. return `userGroup/${userGroup._id}${ext}`;
  44. }
  45. /**
  46. * find all entities with pagination
  47. *
  48. * @see https://github.com/edwardhotchkiss/mongoose-paginate
  49. *
  50. * @static
  51. * @param {any} opts mongoose-paginate options object
  52. * @returns {Promise<any>} mongoose-paginate result object
  53. * @memberof UserGroup
  54. */
  55. static findUserGroupsWithPagination(opts) {
  56. const query = { parent: null };
  57. const options = Object.assign({}, opts);
  58. if (options.page == null) {
  59. options.page = 1;
  60. }
  61. if (options.limit == null) {
  62. options.limit = UserGroup.PAGE_ITEMS;
  63. }
  64. return this.paginate(query, options)
  65. .catch((err) => {
  66. debug('Error on pagination:', err);
  67. });
  68. }
  69. static async findChildUserGroupsByParentIds(parentIds, includeGrandChildren = false) {
  70. if (!Array.isArray(parentIds)) {
  71. throw Error('parentIds must be an array.');
  72. }
  73. const childUserGroups = await this.find({ parent: { $in: parentIds } });
  74. let grandChildUserGroups = null;
  75. if (includeGrandChildren) {
  76. const childUserGroupIds = childUserGroups.map(group => group._id);
  77. grandChildUserGroups = await this.find({ parent: { $in: childUserGroupIds } });
  78. }
  79. return {
  80. childUserGroups,
  81. grandChildUserGroups,
  82. };
  83. }
  84. // Check if registerable
  85. static isRegisterableName(name) {
  86. const query = { name };
  87. return this.findOne(query)
  88. .then((userGroupData) => {
  89. return (userGroupData == null);
  90. });
  91. }
  92. // Delete completely
  93. static async removeCompletelyById(deleteGroupId, action, transferToUserGroupId, user) {
  94. const UserGroupRelation = mongoose.model('UserGroupRelation');
  95. const groupToDelete = await this.findById(deleteGroupId);
  96. if (groupToDelete == null) {
  97. throw new Error('UserGroup data is not exists. id:', deleteGroupId);
  98. }
  99. const deletedGroup = await groupToDelete.remove();
  100. await Promise.all([
  101. UserGroupRelation.removeAllByUserGroup(deletedGroup),
  102. UserGroup.crowi.pageService.handlePrivatePagesForDeletedGroup(deletedGroup, action, transferToUserGroupId, user),
  103. ]);
  104. return deletedGroup;
  105. }
  106. static countUserGroups() {
  107. return this.estimatedDocumentCount();
  108. }
  109. static async createGroup(name, description, parentId) {
  110. // create without parent
  111. if (parentId == null) {
  112. return this.create({ name, description });
  113. }
  114. // create with parent
  115. const parent = await this.findOne({ _id: parentId });
  116. if (parent == null) {
  117. throw Error('Parent does not exist.');
  118. }
  119. return this.create({ name, description, parent });
  120. }
  121. async updateName(name) {
  122. this.name = name;
  123. await this.save();
  124. }
  125. }
  126. module.exports = function(crowi) {
  127. UserGroup.crowi = crowi;
  128. schema.loadClass(UserGroup);
  129. return mongoose.model('UserGroup', schema);
  130. };