Просмотр исходного кода

WIP: GC-1224 refactor page

* refactor findListByStartWith
Yuki Takei 7 лет назад
Родитель
Сommit
0b57bc00c0
2 измененных файлов с 66 добавлено и 121 удалено
  1. 23 58
      src/server/models/page.js
  2. 43 63
      src/server/routes/page.js

+ 23 - 58
src/server/models/page.js

@@ -93,12 +93,10 @@ class PageQueryBuilder {
    *   -> returns '{path}*'
    *
    * *option*
-   *   - includeDeletedPage -- if true, search deleted pages (default: false)
    *   - isRegExpEscapedFromPath -- if true, the regex strings included in `path` is escaped (default: false)
    */
   addConditionToListByStartWith(path, option) {
     const pathCondition = [];
-    const includeDeletedPage = option.includeDeletedPage || false;
     const isRegExpEscapedFromPath = option.isRegExpEscapedFromPath || false;
 
     /*
@@ -121,21 +119,10 @@ class PageQueryBuilder {
     pathCondition.push({path: queryReg});
 
     this.query = this.query
-      .and({ redirectTo: null })
       .and({
         $or: pathCondition
       });
 
-    if (!includeDeletedPage) {
-      this.query = this.query
-        .and({
-          $or: [
-            {status: null},
-            {status: STATUS_PUBLISHED},
-          ]
-        });
-    }
-
     return this;
   }
 
@@ -591,28 +578,16 @@ module.exports = function(crowi) {
 
   /**
    * find pages that start with `path`
-   *
-   * see the comment of `generateQueryToListByStartWith` function
    */
   pageSchema.statics.findListByStartWith = async function(path, user, option) {
     validateCrowi();
 
     const User = crowi.model('User');
 
-    if (!option) {
-      option = {sort: 'updatedAt', desc: -1, offset: 0, limit: 50};
-    }
-    const opt = {
-      sort: option.sort || 'updatedAt',
-      desc: option.desc || -1,
-      offset: option.offset || 0,
-      limit: option.limit || 50
-    };
+    const opt = Object.assign({sort: 'updatedAt', desc: -1}, option);
     const sortOpt = {};
     sortOpt[opt.sort] = opt.desc;
 
-    const isPopulateRevisionBody = option.isPopulateRevisionBody || false;
-
     const builder = new PageQueryBuilder(this.find());
     builder.addConditionToListByStartWith(path, option);
 
@@ -624,25 +599,18 @@ module.exports = function(crowi) {
     }
     builder.addConditionToFilteringByViewer(user, userGroups);
 
-    let q = builder.query
-      .sort(sortOpt)
-      .skip(opt.offset)
-      .limit(opt.limit)
+    const totalCount = await builder.query.exec('count');
+    const q = builder.query
+      .sort(sortOpt).skip(opt.offset).limit(opt.limit)
       .populate({
         path: 'lastUpdateUser',
         model: 'User',
         select: User.USER_PUBLIC_FIELDS
       });
+    const pages = await q.exec('find');
 
-    // retrieve revision data
-    if (isPopulateRevisionBody) {
-      q = q.populate('revision');
-    }
-    else {
-      q = q.populate('revision', '-body');  // exclude body
-    }
-
-    return await q.exec();
+    const result = { pages, totalCount, offset: opt.offset, limit: opt.limit };
+    return result;
   };
 
   /**
@@ -656,21 +624,13 @@ module.exports = function(crowi) {
     validateCrowi();
 
     const User = crowi.model('User');
-    const limit = option.limit || 50;
-    const offset = option.offset || 0;
 
-    const builder = new PageQueryBuilder(
-      this.find({
-        creator: targetUser._id,
-        redirectTo: null,
-      })
-      .populate({
-        path: 'lastUpdateUser',
-        model: 'User',
-        select: User.USER_PUBLIC_FIELDS
-      })
-    );
+    const opt = Object.assign({sort: 'createdAt', desc: -1, offset: 0}, option);
+    const sortOpt = {};
+    sortOpt[opt.sort] = opt.desc;
 
+    const baseQuery = this.find({ creator: targetUser._id });
+    const builder = new PageQueryBuilder(baseQuery)
     // add grant conditions
     let userGroups = null;
     if (currentUser != null) {
@@ -681,10 +641,15 @@ module.exports = function(crowi) {
 
     const totalCount = await builder.query.exec('count');
     const q = builder.query
-      .sort({createdAt: -1}).skip(offset).limit(limit);
+      .sort(sortOpt).skip(opt.offset).limit(opt.limit)
+      .populate({
+        path: 'lastUpdateUser',
+        model: 'User',
+        select: User.USER_PUBLIC_FIELDS
+      });
     const pages = await q.exec('find');
 
-    const result = { pages, totalCount };
+    const result = { pages, totalCount, offset: opt.offset, limit: opt.limit };
     return result;
   };
 
@@ -1155,11 +1120,11 @@ module.exports = function(crowi) {
 
     const pages = await this.findListWithDescendants(path, user, options);
     await Promise.all(pages.map(page => {
-          const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
+      const newPagePath = page.path.replace(pathRegExp, newPagePathPrefix);
       return this.rename(page, newPagePath, user, options);
-        }));
-        pageData.path = newPagePathPrefix;
-        return pageData;
+    }));
+    pageData.path = newPagePathPrefix;
+    return pageData;
   };
 
   /**

+ 43 - 63
src/server/routes/page.js

@@ -60,14 +60,9 @@ module.exports = function(crowi, app) {
     return false;
   }
 
-  // TODO: total とかでちゃんと計算する
-  function generatePager(options) {
+  function generatePager(offset, limit, totalCount) {
     let next = null,
       prev = null;
-    const offset = parseInt(options.offset, 10),
-      limit  = parseInt(options.limit, 10),
-      length = options.length || 0;
-
 
     if (offset > 0) {
       prev = offset - limit;
@@ -76,7 +71,7 @@ module.exports = function(crowi, app) {
       }
     }
 
-    if (length < limit) {
+    if (totalCount < limit) {
       next = null;
     }
     else {
@@ -139,27 +134,27 @@ module.exports = function(crowi, app) {
     const queryOptions = {
       offset: offset,
       limit: limit + 1,
-      isPopulateRevisionBody: Config.isEnabledTimeline(config),
-      includeDeletedPage: path.startsWith('/trash/'),
+      includeTrashed: path.startsWith('/trash/'),
       isRegExpEscapedFromPath,
     };
-    const pageList = await Page.findListWithDescendants(path, requestUser, queryOptions);
-    if (pageList.length > limit) {
-      pageList.pop();
+    const result = await Page.findListWithDescendants(path, requestUser, queryOptions);
+    if (result.pages.length > limit) {
+      result.pages.pop();
     }
 
-    // index page
-    const pagerOptions = {
-      offset: offset,
-      limit: limit
-    };
-    pagerOptions.length = pageList.length;
+    // populate for timeline
+    if (Config.isEnabledTimeline(config)) {
+      await Page.populate(result.pages, {
+        path: 'revision',
+        model: 'Revision',
+      });
+    }
 
     renderVars.viewConfig = {
       seener_threshold: SEENER_THRESHOLD,
     };
-    renderVars.pager = generatePager(pagerOptions);
-    renderVars.pages = pagePathUtils.encodePagesPath(pageList);
+    renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
+    renderVars.pages = pagePathUtils.encodePagesPath(result.pages);
   }
 
   function replacePlaceholdersOfTemplate(template, req) {
@@ -410,20 +405,15 @@ module.exports = function(crowi, app) {
     return res.render(view, renderVars);
   };
 
-  actions.deletedPageListShow = function(req, res) {
+  actions.deletedPageListShow = async function(req, res) {
     const path = '/trash' + getPathFromRequest(req);
     const limit = 50;
     const offset = parseInt(req.query.offset)  || 0;
 
-    // index page
-    const pagerOptions = {
-      offset: offset,
-      limit: limit
-    };
     const queryOptions = {
       offset: offset,
       limit: limit + 1,
-      includeDeletedPage: true,
+      includeTrashed: true,
     };
 
     const renderVars = {
@@ -432,21 +422,16 @@ module.exports = function(crowi, app) {
       pages: [],
     };
 
-    Page.findListWithDescendants(path, req.user, queryOptions)
-    .then(function(pageList) {
+    const result = await Page.findListWithDescendants(path, req.user, queryOptions);
 
-      if (pageList.length > limit) {
-        pageList.pop();
-      }
+    if (result.pages.length > limit) {
+      result.pages.pop();
+    }
 
-      pagerOptions.length = pageList.length;
+    renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
+    renderVars.pages = pagePathUtils.encodePagesPath(result.pages);
+    res.render('customlayout-selector/page_list', renderVars);
 
-      renderVars.pager = generatePager(pagerOptions);
-      renderVars.pages = pagePathUtils.encodePagesPath(pageList);
-      res.render('customlayout-selector/page_list', renderVars);
-    }).catch(function(err) {
-      debug('Error on rendering deletedPageListShow', err);
-    });
   };
 
   actions.search = function(req, res) {
@@ -472,7 +457,7 @@ module.exports = function(crowi, app) {
       res.render('customlayout-selector/page_list', {
         path: '/',
         pages: pagePathUtils.encodePagesPath(pages),
-        pager: generatePager({offset: 0, limit: 50})
+        pager: generatePager(0, 50)
       });
     }).catch(function(err) {
       debug('search error', err);
@@ -505,14 +490,13 @@ module.exports = function(crowi, app) {
    * @apiParam {String} path
    * @apiParam {String} user
    */
-  api.list = function(req, res) {
+  api.list = async function(req, res) {
     const username = req.query.user || null;
     const path = req.query.path || null;
     const limit = + req.query.limit || 50;
     const offset = parseInt(req.query.offset) || 0;
 
-    const pagerOptions = { offset: offset, limit: limit };
-    const queryOptions = { offset: offset, limit: limit + 1};
+    const queryOptions = { offset, limit: limit + 1 };
 
     // Accepts only one of these
     if (username === null && path === null) {
@@ -522,33 +506,29 @@ module.exports = function(crowi, app) {
       return res.json(ApiResponse.error('Parameter user or path is required.'));
     }
 
-    let pageFetcher;
-    if (path === null) {
-      pageFetcher = User.findUserByUsername(username)
-      .then(function(user) {
+    try {
+      let result = null;
+      if (path == null) {
+        const user = await User.findUserByUsername(username);
         if (user === null) {
           throw new Error('The user not found.');
         }
-        return Page.findListByCreator(user, queryOptions, req.user);
-      });
-    }
-    else {
-      pageFetcher = Page.findListByStartWith(path, req.user, queryOptions);
-    }
+        result = await Page.findListByCreator(user, req.user, queryOptions);
+      }
+      else {
+        result = await Page.findListByStartWith(path, req.user, queryOptions);
+      }
 
-    pageFetcher
-    .then(function(pages) {
-      if (pages.length > limit) {
-        pages.pop();
+      if (result.pages.length > limit) {
+        result.pages.pop();
       }
-      pagerOptions.length = pages.length;
 
-      const result = {};
-      result.pages = pagePathUtils.encodePagesPath(pages);
+      result.pages = pagePathUtils.encodePagesPath(result.pages);
       return res.json(ApiResponse.success(result));
-    }).catch(function(err) {
+    }
+    catch (err) {
       return res.json(ApiResponse.error(err));
-    });
+    }
   };
 
   /**
@@ -983,7 +963,7 @@ module.exports = function(crowi, app) {
     const isExist = await Page.count({ path: newPagePath }) > 0;
     if (isExist) {
       // if page found, cannot cannot rename to that path
-      return res.json(ApiResponse.error(`このページ名は作成できません (${newPagePath})。ページが存在します。`));
+      return res.json(ApiResponse.error('The page already exists'));
     }
 
     let page;