lsx.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. const { customTagUtils } = require('@growi/core');
  2. const { OptionParser } = customTagUtils;
  3. const DEFAULT_PAGES_NUM = 50;
  4. class Lsx {
  5. /**
  6. * add depth condition that limit fetched pages
  7. *
  8. * @static
  9. * @param {any} query
  10. * @param {any} pagePath
  11. * @param {any} optionsDepth
  12. * @returns
  13. *
  14. * @memberOf Lsx
  15. */
  16. static addDepthCondition(query, pagePath, optionsDepth) {
  17. // when option strings is 'depth=', the option value is true
  18. if (optionsDepth == null || optionsDepth === true) {
  19. throw new Error('The value of depth option is invalid.');
  20. }
  21. const range = OptionParser.parseRange(optionsDepth);
  22. const start = range.start;
  23. const end = range.end;
  24. if (start < 1 || end < 1) {
  25. throw new Error(`specified depth is [${start}:${end}] : start and end are must be larger than 1`);
  26. }
  27. // count slash
  28. const slashNum = pagePath.split('/').length - 1;
  29. const depthStart = slashNum; // start is not affect to fetch page
  30. const depthEnd = slashNum + end - 1;
  31. return query.and({
  32. path: new RegExp(`^(\\/[^\\/]*){${depthStart},${depthEnd}}$`),
  33. });
  34. }
  35. /**
  36. * add num condition that limit fetched pages
  37. *
  38. * @static
  39. * @param {any} query
  40. * @param {any} pagePath
  41. * @param {number|string} optionsNum
  42. * @returns
  43. *
  44. * @memberOf Lsx
  45. */
  46. static addNumCondition(query, pagePath, optionsNum) {
  47. // when option strings is 'num=', the option value is true
  48. if (optionsNum == null || optionsNum === true) {
  49. throw new Error('The value of num option is invalid.');
  50. }
  51. if (typeof optionsNum === 'number') {
  52. return query.limit(optionsNum);
  53. }
  54. const range = OptionParser.parseRange(optionsNum);
  55. const start = range.start;
  56. const end = range.end;
  57. if (start < 1 || end < 1) {
  58. throw new Error(`specified num is [${start}:${end}] : start and end are must be larger than 1`);
  59. }
  60. const skip = start - 1;
  61. const limit = end - skip;
  62. return query.skip(skip).limit(limit);
  63. }
  64. /**
  65. * add filter condition that filter fetched pages
  66. *
  67. * @static
  68. * @param {any} query
  69. * @param {any} pagePath
  70. * @param {any} optionsFilter
  71. * @param {boolean} isExceptFilter
  72. * @returns
  73. *
  74. * @memberOf Lsx
  75. */
  76. static addFilterCondition(query, pagePath, optionsFilter, isExceptFilter = false) {
  77. // when option strings is 'filter=', the option value is true
  78. if (optionsFilter == null || optionsFilter === true) {
  79. throw new Error('filter option require value in regular expression.');
  80. }
  81. let filterPath = '';
  82. if (optionsFilter.charAt(0) === '^') {
  83. // move '^' to the first of path
  84. filterPath = new RegExp(`^${pagePath}${optionsFilter.slice(1, optionsFilter.length)}`);
  85. }
  86. else {
  87. filterPath = new RegExp(`^${pagePath}.*${optionsFilter}`);
  88. }
  89. if (isExceptFilter) {
  90. return query.and({
  91. path: { $not: filterPath },
  92. });
  93. }
  94. return query.and({
  95. path: filterPath,
  96. });
  97. }
  98. static addExceptCondition(query, pagePath, optionsFilter) {
  99. return this.addFilterCondition(query, pagePath, optionsFilter, true);
  100. }
  101. /**
  102. * add sort condition(sort key & sort order)
  103. *
  104. * If only the reverse option is specified, the sort key is 'path'.
  105. * If only the sort key is specified, the sort order is the ascending order.
  106. *
  107. * @static
  108. * @param {any} query
  109. * @param {string} pagePath
  110. * @param {string} optionsSort
  111. * @param {string} optionsReverse
  112. * @returns
  113. *
  114. * @memberOf Lsx
  115. */
  116. static addSortCondition(query, pagePath, optionsSortArg, optionsReverse) {
  117. // init sort key
  118. const optionsSort = optionsSortArg ?? 'path';
  119. // the default sort order
  120. const isReversed = optionsReverse === 'true';
  121. if (optionsSort !== 'path' && optionsSort !== 'createdAt' && optionsSort !== 'updatedAt') {
  122. throw new Error(`The specified value '${optionsSort}' for the sort option is invalid. It must be 'path', 'createdAt' or 'updatedAt'.`);
  123. }
  124. const sortOption = {};
  125. sortOption[optionsSort] = isReversed ? -1 : 1;
  126. return query.sort(sortOption);
  127. }
  128. }
  129. module.exports = (crowi, app) => {
  130. const Page = crowi.model('Page');
  131. const ApiResponse = crowi.require('../util/apiResponse');
  132. const actions = {};
  133. /**
  134. *
  135. * @param {*} pagePath
  136. * @param {*} user
  137. *
  138. * @return {Promise<Query>} query
  139. */
  140. async function generateBaseQueryBuilder(pagePath, user) {
  141. let baseQuery = Page.find();
  142. if (Page.PageQueryBuilder == null) {
  143. if (Page.generateQueryToListWithDescendants != null) { // for Backward compatibility (<= GROWI v3.2.x)
  144. baseQuery = Page.generateQueryToListWithDescendants(pagePath, user, {});
  145. }
  146. else if (Page.generateQueryToListByStartWith != null) { // for Backward compatibility (<= crowi-plus v2.0.7)
  147. baseQuery = Page.generateQueryToListByStartWith(pagePath, user, {});
  148. }
  149. // return dummy PageQueryBuilder object
  150. return Promise.resolve({ query: baseQuery });
  151. }
  152. const builder = new Page.PageQueryBuilder(baseQuery);
  153. if (builder.addConditionToListOnlyDescendants == null) { // for Backward compatibility (<= GROWI v4.0.x)
  154. builder.addConditionToListWithDescendants(pagePath);
  155. }
  156. else {
  157. builder.addConditionToListOnlyDescendants(pagePath);
  158. }
  159. builder
  160. .addConditionToExcludeTrashed();
  161. return Page.addConditionToFilteringByViewerForList(builder, user);
  162. }
  163. actions.listPages = async(req, res) => {
  164. const user = req.user;
  165. let pagePath;
  166. let options;
  167. try {
  168. pagePath = req.query.pagePath;
  169. options = JSON.parse(req.query.options);
  170. }
  171. catch (error) {
  172. return res.status(400).send(error);
  173. }
  174. const builder = await generateBaseQueryBuilder(pagePath, user);
  175. // count viewers of `/`
  176. let toppageViewersCount;
  177. try {
  178. const aggRes = await Page.aggregate([
  179. { $match: { path: '/' } },
  180. { $project: { count: { $size: '$seenUsers' } } },
  181. ]);
  182. toppageViewersCount = aggRes.length > 0
  183. ? aggRes[0].count
  184. : 1;
  185. }
  186. catch (error) {
  187. return res.status(500).send(error);
  188. }
  189. let query = builder.query;
  190. try {
  191. // depth
  192. if (options.depth != null) {
  193. query = Lsx.addDepthCondition(query, pagePath, options.depth);
  194. }
  195. // filter
  196. if (options.filter != null) {
  197. query = Lsx.addFilterCondition(query, pagePath, options.filter);
  198. }
  199. if (options.except != null) {
  200. query = Lsx.addExceptCondition(query, pagePath, options.except);
  201. }
  202. // num
  203. const optionsNum = options.num || DEFAULT_PAGES_NUM;
  204. query = Lsx.addNumCondition(query, pagePath, optionsNum);
  205. // sort
  206. query = Lsx.addSortCondition(query, pagePath, options.sort, options.reverse);
  207. const pages = await query.exec();
  208. res.status(200).send({ pages, toppageViewersCount });
  209. }
  210. catch (error) {
  211. return res.status(500).send(error);
  212. }
  213. };
  214. return actions;
  215. };