DbSearcher.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //const _ = require('lodash');
  2. const utils = require('./utils');
  3. class DbSearcher {
  4. constructor(db) {
  5. this.db = db;
  6. }
  7. async selectAuthorIds(query) {
  8. const db = this.db;
  9. let authorRows;
  10. //сначала выберем все id авторов по фильтру
  11. //порядок id соответсвует ASC-сортировке по author
  12. if (query.author) {
  13. //
  14. } else {
  15. authorRows = await db.select({
  16. table: 'author',
  17. map: `(r) => ({id: r.id})`,
  18. });
  19. }
  20. let authorIds = new Set();
  21. for (const row of authorRows)
  22. authorIds.add(row.id);
  23. const idsArr = [];
  24. idsArr.push(authorIds);
  25. //серии
  26. //названия
  27. //жанры
  28. //языки
  29. if (idsArr.length > 1)
  30. authorIds = utils.intersectSet(idsArr);
  31. //сортировка
  32. authorIds = Array.from(authorIds);
  33. authorIds.sort();
  34. return authorIds;
  35. }
  36. async getAuthorIds(query) {
  37. const db = this.db;
  38. if (!db.searchCache)
  39. db.searchCache = {};
  40. /*const q = query;
  41. const key = JSON.stringify([q.author, ]);
  42. query);
  43. delete q.limit;
  44. q = */
  45. return await this.selectAuthorIds(query);
  46. }
  47. async search(query) {
  48. const db = this.db;
  49. const authorIds = await this.getAuthorIds(query);
  50. const totalFound = authorIds.length;
  51. const limit = (query.limit ? query.limit : 1000);
  52. //выборка найденных авторов
  53. let result = await db.select({
  54. table: 'author',
  55. map: `(r) => ({id: r.id, author: r.author})`,
  56. where: `@@id(${db.esc(authorIds)})`
  57. });
  58. result = result.slice(0, limit);
  59. return {result, totalFound};
  60. }
  61. }
  62. module.exports = DbSearcher;