lsx.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. let isReversed = false;
  121. if (optionsSort != null) {
  122. if (optionsSort !== 'path' && optionsSort !== 'createdAt' && optionsSort !== 'updatedAt') {
  123. throw new Error(`The specified value '${optionsSort}' for the sort option is invalid. It must be 'path', 'createdAt' or 'updatedAt'.`);
  124. }
  125. }
  126. if (optionsReverse != null) {
  127. if (optionsReverse !== 'true' && optionsReverse !== 'false') {
  128. throw new Error(`The specified value '${optionsReverse}' for the reverse option is invalid. It must be 'true' or 'false'.`);
  129. }
  130. isReversed = (optionsReverse === 'true');
  131. }
  132. const sortOption = {};
  133. sortOption[optionsSort] = isReversed ? -1 : 1;
  134. return query.sort(sortOption);
  135. }
  136. }
  137. module.exports = (crowi, app) => {
  138. const Page = crowi.model('Page');
  139. const ApiResponse = crowi.require('../util/apiResponse');
  140. const actions = {};
  141. /**
  142. *
  143. * @param {*} pagePath
  144. * @param {*} user
  145. *
  146. * @return {Promise<Query>} query
  147. */
  148. async function generateBaseQueryBuilder(pagePath, user) {
  149. let baseQuery = Page.find();
  150. if (Page.PageQueryBuilder == null) {
  151. if (Page.generateQueryToListWithDescendants != null) { // for Backward compatibility (<= GROWI v3.2.x)
  152. baseQuery = Page.generateQueryToListWithDescendants(pagePath, user, {});
  153. }
  154. else if (Page.generateQueryToListByStartWith != null) { // for Backward compatibility (<= crowi-plus v2.0.7)
  155. baseQuery = Page.generateQueryToListByStartWith(pagePath, user, {});
  156. }
  157. // return dummy PageQueryBuilder object
  158. return Promise.resolve({ query: baseQuery });
  159. }
  160. const builder = new Page.PageQueryBuilder(baseQuery);
  161. if (builder.addConditionToListOnlyDescendants == null) { // for Backward compatibility (<= GROWI v4.0.x)
  162. builder.addConditionToListWithDescendants(pagePath);
  163. }
  164. else {
  165. builder.addConditionToListOnlyDescendants(pagePath);
  166. }
  167. builder
  168. .addConditionToExcludeTrashed();
  169. return Page.addConditionToFilteringByViewerForList(builder, user);
  170. }
  171. actions.listPages = async(req, res) => {
  172. const user = req.user;
  173. const pagePath = req.query.pagePath;
  174. const options = JSON.parse(req.query.options);
  175. const builder = await generateBaseQueryBuilder(pagePath, user);
  176. let query = builder.query;
  177. try {
  178. // depth
  179. if (options.depth != null) {
  180. query = Lsx.addDepthCondition(query, pagePath, options.depth);
  181. }
  182. // filter
  183. if (options.filter != null) {
  184. query = Lsx.addFilterCondition(query, pagePath, options.filter);
  185. }
  186. if (options.except != null) {
  187. query = Lsx.addExceptCondition(query, pagePath, options.except);
  188. }
  189. // num
  190. const optionsNum = options.num || DEFAULT_PAGES_NUM;
  191. query = Lsx.addNumCondition(query, pagePath, optionsNum);
  192. // sort
  193. query = Lsx.addSortCondition(query, pagePath, options.sort, options.reverse);
  194. const pages = await query.exec();
  195. res.json(ApiResponse.success({ pages }));
  196. }
  197. catch (error) {
  198. return res.json(ApiResponse.error(error));
  199. }
  200. };
  201. return actions;
  202. };