model-manager.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. get all() {
  25. return this.models;
  26. }
  27. getModelsTopoSortedByForeignKey() {
  28. const models = /* @__PURE__ */ new Map();
  29. const sorter = new Toposort();
  30. for (const model of this.models) {
  31. let deps = [];
  32. let tableName = model.getTableName();
  33. if (_.isObject(tableName)) {
  34. tableName = `${tableName.schema}.${tableName.tableName}`;
  35. }
  36. models.set(tableName, model);
  37. for (const attrName in model.rawAttributes) {
  38. if (Object.prototype.hasOwnProperty.call(model.rawAttributes, attrName)) {
  39. const attribute = model.rawAttributes[attrName];
  40. if (attribute.references) {
  41. let dep = attribute.references.model;
  42. if (_.isObject(dep)) {
  43. dep = `${dep.schema}.${dep.tableName}`;
  44. }
  45. deps.push(dep);
  46. }
  47. }
  48. }
  49. deps = deps.filter((dep) => tableName !== dep);
  50. sorter.add(tableName, deps);
  51. }
  52. let sorted;
  53. try {
  54. sorted = sorter.sort();
  55. } catch (e) {
  56. if (!e.message.startsWith("Cyclic dependency found.")) {
  57. throw e;
  58. }
  59. return null;
  60. }
  61. return sorted.map((modelName) => {
  62. return models.get(modelName);
  63. }).filter(Boolean);
  64. }
  65. forEachModel(iterator, options) {
  66. const sortedModels = this.getModelsTopoSortedByForeignKey();
  67. if (sortedModels == null) {
  68. throw new Error("Cyclic dependency found.");
  69. }
  70. options = _.defaults(options || {}, {
  71. reverse: true
  72. });
  73. if (options.reverse) {
  74. sortedModels.reverse();
  75. }
  76. for (const model of sortedModels) {
  77. iterator(model);
  78. }
  79. }
  80. }
  81. module.exports = ModelManager;
  82. module.exports.ModelManager = ModelManager;
  83. module.exports.default = ModelManager;
  84. //# sourceMappingURL=model-manager.js.map