model-manager.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. "use strict";
  2. const Toposort = require("toposort-class");
  3. const _ = require("lodash");
  4. class ModelManager {
  5. constructor(sequelize) {
  6. this.models = [];
  7. this.sequelize = sequelize;
  8. }
  9. addModel(model) {
  10. this.models.push(model);
  11. this.sequelize.models[model.name] = model;
  12. return model;
  13. }
  14. removeModel(modelToRemove) {
  15. this.models = this.models.filter((model) => model.name !== modelToRemove.name);
  16. delete this.sequelize.models[modelToRemove.name];
  17. }
  18. getModel(against, options) {
  19. options = _.defaults(options || {}, {
  20. attribute: "name"
  21. });
  22. return this.models.find((model) => model[options.attribute] === against);
  23. }
  24. findModel(callback) {
  25. return this.models.find(callback);
  26. }
  27. get all() {
  28. return this.models;
  29. }
  30. getModelsTopoSortedByForeignKey() {
  31. const models = /* @__PURE__ */ new Map();
  32. const sorter = new Toposort();
  33. for (const model of this.models) {
  34. let deps = [];
  35. let tableName = model.getTableName();
  36. if (_.isObject(tableName)) {
  37. tableName = `${tableName.schema}.${tableName.tableName}`;
  38. }
  39. models.set(tableName, model);
  40. for (const attrName in model.rawAttributes) {
  41. if (Object.prototype.hasOwnProperty.call(model.rawAttributes, attrName)) {
  42. const attribute = model.rawAttributes[attrName];
  43. if (attribute.references) {
  44. let dep = attribute.references.model;
  45. if (_.isObject(dep)) {
  46. dep = `${dep.schema}.${dep.tableName}`;
  47. }
  48. deps.push(dep);
  49. }
  50. }
  51. }
  52. deps = deps.filter((dep) => tableName !== dep);
  53. sorter.add(tableName, deps);
  54. }
  55. let sorted;
  56. try {
  57. sorted = sorter.sort();
  58. } catch (e) {
  59. if (!e.message.startsWith("Cyclic dependency found.")) {
  60. throw e;
  61. }
  62. return null;
  63. }
  64. return sorted.map((modelName) => {
  65. return models.get(modelName);
  66. }).filter(Boolean);
  67. }
  68. forEachModel(iterator, options) {
  69. const sortedModels = this.getModelsTopoSortedByForeignKey();
  70. if (sortedModels == null) {
  71. throw new Error("Cyclic dependency found.");
  72. }
  73. options = _.defaults(options || {}, {
  74. reverse: true
  75. });
  76. if (options.reverse) {
  77. sortedModels.reverse();
  78. }
  79. for (const model of sortedModels) {
  80. iterator(model);
  81. }
  82. }
  83. }
  84. module.exports = ModelManager;
  85. module.exports.ModelManager = ModelManager;
  86. module.exports.default = ModelManager;
  87. //# sourceMappingURL=model-manager.js.map