util.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. const async = require("async");
  3. const coreClass = require("../core");
  4. const config = require('config');
  5. module.exports = class extends coreClass {
  6. constructor(name, moduleManager) {
  7. super(name, moduleManager);
  8. this.dependsOn = ["mongo"];
  9. }
  10. initialize() {
  11. return new Promise((resolve, reject) => {
  12. this.setStage(1);
  13. this.mongo = this.moduleManager.modules["mongo"];
  14. this._autosuggestCache = {};
  15. this._autosuggestMap = {};
  16. async.waterfall([
  17. (next) => {
  18. this.mongo.models.then(models => {
  19. models.accountSchema.find({}, null, { sort: "-version", limit: 1 }, next);
  20. });
  21. },
  22. (schemas, next) => {
  23. schemas[0].fields.forEach(field => {
  24. field.fieldTypes.forEach(fieldType => {
  25. if (fieldType.type === "text" && fieldType.autosuggestGroup) {
  26. this._autosuggestMap[`${field.fieldId}.${fieldType.fieldTypeId}`] = fieldType.autosuggestGroup;
  27. this._autosuggestCache[fieldType.autosuggestGroup] = [];
  28. }
  29. });
  30. });
  31. this.mongo.models.then(models => {
  32. models.account.find({}, next);
  33. });
  34. },
  35. (accounts, next) => {
  36. accounts.forEach(account => {
  37. Object.keys(this._autosuggestMap).forEach(key => {
  38. let autosuggestGroup = this._autosuggestMap[key];
  39. let fieldId = key.split(".")[0];
  40. let fieldTypeId = key.split(".")[1];
  41. account.fields[fieldId].forEach(field => {
  42. if (this._autosuggestCache[autosuggestGroup].indexOf(field[fieldTypeId]) === -1)
  43. this._autosuggestCache[autosuggestGroup].push(field[fieldTypeId]);
  44. });
  45. });
  46. });
  47. next();
  48. }
  49. ], (err) => {
  50. if (err) reject(new Error(err));
  51. else resolve();
  52. });
  53. })
  54. }
  55. get autosuggestCache() {
  56. return new Promise(async resolve => {
  57. try { await this._validateHook(); } catch { return; }
  58. resolve(this._autosuggestCache);
  59. });
  60. }
  61. get autosuggestMap() {
  62. return new Promise(async resolve => {
  63. try { await this._validateHook(); } catch { return; }
  64. resolve(this._autosuggestMap);
  65. });
  66. }
  67. async addAutosuggestAccount(account) {
  68. try { await this._validateHook(); } catch { return; }
  69. Object.keys(this._autosuggestMap).forEach(key => {
  70. let autosuggestGroup = this._autosuggestMap[key];
  71. let fieldId = key.split(".")[0];
  72. let fieldTypeId = key.split(".")[1];
  73. account.fields[fieldId].forEach(field => {
  74. if (this._autosuggestCache[autosuggestGroup].indexOf(field[fieldTypeId]) === -1)
  75. this._autosuggestCache[autosuggestGroup].push(field[fieldTypeId]);
  76. });
  77. });
  78. }
  79. }