Răsfoiți Sursa

remake method for get tag list

yusuketk 7 ani în urmă
părinte
comite
0597944eb7
3 a modificat fișierele cu 38 adăugiri și 16 ștergeri
  1. 3 3
      src/client/js/components/TagsList.jsx
  2. 33 0
      src/server/models/tag.js
  3. 2 13
      src/server/routes/tag.js

+ 3 - 3
src/client/js/components/TagsList.jsx

@@ -22,12 +22,12 @@ export default class TagsList extends React.Component {
   }
 
   async getTagList(selectPageNumber) {
-    const limit = 3;
+    const limit = 10;
     const offset = (selectPageNumber - 1) * limit;
     const res = await this.props.crowi.apiGet('/tags.list', { limit, offset });
 
-    const totalCount = res.totalCount;
-    const tagData = res.tagData;
+    const totalCount = res.result.pages.length;
+    const tagData = res.result.pages.tagData;
     const activePage = selectPageNumber;
     const paginationNumbers = this.calculatePagination(limit, totalCount, activePage);
 

+ 33 - 0
src/server/models/tag.js

@@ -15,6 +15,21 @@ const schema = new mongoose.Schema({
 });
 schema.plugin(mongoosePaginate);
 
+class TagQueryBuilder {
+
+  constructor(query) {
+    this.query = query;
+  }
+
+  addConditionToPagenate(offset, limit, sortOpt) {
+    this.query = this.query
+      .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
+
+    return this;
+  }
+
+}
+
 /**
  * Tag Class
  *
@@ -30,6 +45,24 @@ class Tag {
     return tag;
   }
 
+  static async findList(option) {
+    const opt = Object.assign({ sort: 'count', desc: -1 }, option);
+    const builder = new TagQueryBuilder(this.find({}));
+    const sortOpt = {};
+    sortOpt[opt.sort] = opt.desc;
+
+    // count
+    const totalCount = await builder.query.exec('count');
+
+    // find
+    builder.addConditionToPagenate(opt.offset, opt.limit, sortOpt);
+    const tags = await builder.query.exec('find');
+    const result = {
+      tags, totalCount, offset: opt.offset, limit: opt.limit,
+    };
+    return result;
+  }
+
 }
 
 module.exports = function() {

+ 2 - 13
src/server/routes/tag.js

@@ -33,28 +33,17 @@ module.exports = function(crowi, app) {
    * @apiParam {Number} offset
    */
   api.list = async function(req, res) {
-    const PageTagRelation = crowi.model('PageTagRelation');
     const limit = +req.query.limit || 50;
     const offset = +req.query.offset || 0;
     const queryOptions = { offset, limit };
-    const result = [];
-
-    const tags = await Tag.find();
 
     try {
-      /* eslint-disable no-await-in-loop */
-      for (const tag of tags) {
-        const data = {};
-        data.tagName = tag.name;
-        data.countPage = await PageTagRelation.count({ relatedTag: tag.id });
-        result.push(data);
-      }
+      const result = await Tag.findList(queryOptions);
+      return res.json(ApiResponse.success({ result }));
     }
     catch (err) {
       return res.json(ApiResponse.error(err));
     }
-
-    return res.json(ApiResponse.success({ result }));
   };