SearchPage.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const BasePage = require('./BasePage');
  2. class SearchPage extends BasePage {
  3. constructor(config) {
  4. super(config);
  5. this.id = 'search';
  6. this.title = 'Поиск';
  7. }
  8. async body(req) {
  9. const result = {};
  10. const query = {
  11. type: req.query.type || '',
  12. term: req.query.term || '',
  13. page: parseInt(req.query.page, 10) || 1,
  14. };
  15. let entry = [];
  16. if (query.type) {
  17. if (['author', 'series', 'title'].includes(query.type)) {
  18. const from = query.type;
  19. const page = query.page;
  20. const limit = 100;
  21. const offset = (page - 1)*limit;
  22. const queryRes = await this.webWorker.search(from, {[from]: query.term, del: 0, offset, limit});
  23. const found = queryRes.found;
  24. for (let i = 0; i < found.length; i++) {
  25. if (i >= limit)
  26. break;
  27. const row = found[i];
  28. entry.push(
  29. this.makeEntry({
  30. id: row.id,
  31. title: row[from],
  32. link: this.navLink({href: `/${from}?${from}==${encodeURIComponent(row[from])}`}),
  33. }),
  34. );
  35. }
  36. if (queryRes.totalFound > offset + found.length) {
  37. entry.push(
  38. this.makeEntry({
  39. id: 'next_page',
  40. title: '[Следующая страница]',
  41. link: this.navLink({href: `/${this.id}?type=${from}&term=${encodeURIComponent(query.term)}&page=${page + 1}`}),
  42. }),
  43. );
  44. }
  45. }
  46. } else {
  47. //корневой раздел
  48. entry = [
  49. this.makeEntry({
  50. id: 'search_author',
  51. title: 'Поиск авторов',
  52. link: this.navLink({href: `/${this.id}?type=author&term=${encodeURIComponent(query.term)}`}),
  53. }),
  54. this.makeEntry({
  55. id: 'search_series',
  56. title: 'Поиск серий',
  57. link: this.navLink({href: `/${this.id}?type=series&term=${encodeURIComponent(query.term)}`}),
  58. }),
  59. this.makeEntry({
  60. id: 'search_title',
  61. title: 'Поиск книг',
  62. link: this.navLink({href: `/${this.id}?type=title&term=${encodeURIComponent(query.term)}`}),
  63. }),
  64. ]
  65. }
  66. result.entry = entry;
  67. return this.makeBody(result, req);
  68. }
  69. }
  70. module.exports = SearchPage;