bookmark-folder.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { isValidObjectId } from '@growi/core/src/utils/objectid-utils';
  2. import monggoose, {
  3. Types, Document, Model, Schema,
  4. } from 'mongoose';
  5. import { IBookmarkFolder, BookmarkFolderItems, MyBookmarkList } from '~/interfaces/bookmark-info';
  6. import { IPageHasId } from '~/interfaces/page';
  7. import loggerFactory from '../../utils/logger';
  8. import { getOrCreateModel } from '../util/mongoose-utils';
  9. import { InvalidParentBookmarkFolderError } from './errors';
  10. const logger = loggerFactory('growi:models:bookmark-folder');
  11. const Bookmark = monggoose.model('Bookmark');
  12. export interface BookmarkFolderDocument extends Document {
  13. _id: Types.ObjectId
  14. name: string
  15. owner: Types.ObjectId
  16. parent?: this[]
  17. bookmarks?: Types.ObjectId[]
  18. }
  19. export interface BookmarkFolderModel extends Model<BookmarkFolderDocument>{
  20. createByParameters(params: IBookmarkFolder): Promise<BookmarkFolderDocument>
  21. findFolderAndChildren(user: Types.ObjectId | string, parentId?: Types.ObjectId | string): Promise<BookmarkFolderItems[]>
  22. deleteFolderAndChildren(bookmarkFolderId: Types.ObjectId | string): Promise<{deletedCount: number}>
  23. updateBookmarkFolder(bookmarkFolderId: string, name: string, parent: string | null): Promise<BookmarkFolderDocument>
  24. insertOrUpdateBookmarkedPage(pageId: IPageHasId, userId: Types.ObjectId | string, folderId: string | null): Promise<BookmarkFolderDocument | null>
  25. findUserRootBookmarksItem(userId: Types.ObjectId| string): Promise<MyBookmarkList>
  26. }
  27. const bookmarkFolderSchema = new Schema<BookmarkFolderDocument, BookmarkFolderModel>({
  28. name: { type: String },
  29. owner: { type: Schema.Types.ObjectId, ref: 'User', index: true },
  30. parent: { type: Schema.Types.ObjectId, ref: 'BookmarkFolder', required: false },
  31. bookmarks: {
  32. type: [{
  33. type: Schema.Types.ObjectId, ref: 'Bookmark', required: false,
  34. }],
  35. required: false,
  36. default: [],
  37. },
  38. }, {
  39. toObject: { virtuals: true },
  40. });
  41. bookmarkFolderSchema.virtual('children', {
  42. ref: 'BookmarkFolder',
  43. localField: '_id',
  44. foreignField: 'parent',
  45. });
  46. bookmarkFolderSchema.statics.createByParameters = async function(params: IBookmarkFolder): Promise<BookmarkFolderDocument> {
  47. const { name, owner, parent } = params;
  48. let bookmarkFolder: BookmarkFolderDocument;
  49. if (parent == null) {
  50. bookmarkFolder = await this.create({ name, owner });
  51. }
  52. else {
  53. // Check if parent folder id is valid and parent folder exists
  54. const isParentFolderIdValid = isValidObjectId(parent as string);
  55. if (!isParentFolderIdValid) {
  56. throw new InvalidParentBookmarkFolderError('Parent folder id is invalid');
  57. }
  58. const parentFolder = await this.findById(parent);
  59. if (parentFolder == null) {
  60. throw new InvalidParentBookmarkFolderError('Parent folder not found');
  61. }
  62. bookmarkFolder = await this.create({ name, owner, parent: parentFolder._id });
  63. }
  64. return bookmarkFolder;
  65. };
  66. bookmarkFolderSchema.statics.findFolderAndChildren = async function(
  67. userId: Types.ObjectId | string,
  68. parentId?: Types.ObjectId | string,
  69. ): Promise<BookmarkFolderItems[]> {
  70. let parentFolder: BookmarkFolderDocument | null;
  71. let query = {};
  72. // Load child bookmark folders
  73. if (parentId != null) {
  74. parentFolder = await this.findById(parentId);
  75. if (parentFolder != null) {
  76. query = { owner: userId, parent: parentFolder };
  77. }
  78. else {
  79. throw new InvalidParentBookmarkFolderError('Parent folder not found');
  80. }
  81. }
  82. // Load initial / root bookmark folders
  83. else {
  84. query = { owner: userId, parent: null };
  85. }
  86. const bookmarkFolders: BookmarkFolderItems[] = await this.find(query)
  87. .populate({ path: 'children' })
  88. .populate({
  89. path: 'bookmarks',
  90. model: 'Bookmark',
  91. populate: {
  92. path: 'page',
  93. model: 'Page',
  94. },
  95. });
  96. return bookmarkFolders;
  97. };
  98. bookmarkFolderSchema.statics.deleteFolderAndChildren = async function(bookmarkFolderId: Types.ObjectId | string): Promise<{deletedCount: number}> {
  99. const bookmarkFolder = await this.findById(bookmarkFolderId);
  100. // Delete parent and all children folder
  101. let deletedCount = 0;
  102. if (bookmarkFolder != null) {
  103. // Delete Bookmarks
  104. const bookmarks = bookmarkFolder?.bookmarks;
  105. if (bookmarks && bookmarks.length > 0) {
  106. await Bookmark.deleteMany({ _id: { $in: bookmarks } });
  107. }
  108. // Delete all child recursively and update deleted count
  109. const childFolders = await this.find({ parent: bookmarkFolder });
  110. await Promise.all(childFolders.map(async(child) => {
  111. const deletedChildFolder = await this.deleteFolderAndChildren(child._id);
  112. deletedCount += deletedChildFolder.deletedCount;
  113. }));
  114. const deletedChild = await this.deleteMany({ parent: bookmarkFolder });
  115. deletedCount += deletedChild.deletedCount + 1;
  116. bookmarkFolder.delete();
  117. }
  118. return { deletedCount };
  119. };
  120. bookmarkFolderSchema.statics.updateBookmarkFolder = async function(bookmarkFolderId: string, name: string, parentId: string | null):
  121. Promise<BookmarkFolderDocument> {
  122. const updateFields: {name: string, parent: Types.ObjectId | null} = {
  123. name: '',
  124. parent: null,
  125. };
  126. updateFields.name = name;
  127. const parentFolder = parentId ? await this.findById(parentId) : null;
  128. updateFields.parent = parentFolder?._id ?? null;
  129. const bookmarkFolder = await this.findByIdAndUpdate(bookmarkFolderId, { $set: updateFields }, { new: true });
  130. if (bookmarkFolder == null) {
  131. throw new Error('Update bookmark folder failed');
  132. }
  133. return bookmarkFolder;
  134. };
  135. bookmarkFolderSchema.statics.insertOrUpdateBookmarkedPage = async function(pageId: IPageHasId, userId: Types.ObjectId | string, folderId: string | null):
  136. Promise<BookmarkFolderDocument | null> {
  137. // Create bookmark or update existing
  138. const bookmarkedPage = await Bookmark.findOneAndUpdate({ page: pageId, user: userId }, { page: pageId, user: userId }, { new: true, upsert: true });
  139. // Remove existing bookmark in bookmark folder
  140. await this.updateMany({}, { $pull: { bookmarks: bookmarkedPage._id } });
  141. // Insert bookmark into bookmark folder
  142. if (folderId != null) {
  143. const bookmarkFolder = await this.findByIdAndUpdate(folderId, { $addToSet: { bookmarks: bookmarkedPage } }, { new: true, upsert: true });
  144. return bookmarkFolder;
  145. }
  146. return null;
  147. };
  148. bookmarkFolderSchema.statics.findUserRootBookmarksItem = async function(userId: Types.ObjectId | string): Promise<MyBookmarkList> {
  149. const bookmarkIdsInFolders = await this.distinct('bookmarks', { owner: userId });
  150. const userRootBookmarks: MyBookmarkList = await Bookmark.find({
  151. _id: { $nin: bookmarkIdsInFolders },
  152. }).populate({
  153. path: 'page',
  154. model: 'Page',
  155. populate: {
  156. path: 'lastUpdateUser',
  157. model: 'User',
  158. },
  159. });
  160. return userRootBookmarks;
  161. };
  162. export default getOrCreateModel<BookmarkFolderDocument, BookmarkFolderModel>('BookmarkFolder', bookmarkFolderSchema);