UNPKG

2.31 kBJavaScriptView Raw
1'use strict';
2
3const Toposort = require('toposort-class');
4const _ = require('lodash');
5
6class ModelManager {
7 constructor(sequelize) {
8 this.models = [];
9 this.sequelize = sequelize;
10 }
11
12 addModel(model) {
13 this.models.push(model);
14 this.sequelize.models[model.name] = model;
15
16 return model;
17 }
18
19 removeModel(modelToRemove) {
20 this.models = this.models.filter(model => model.name !== modelToRemove.name);
21
22 delete this.sequelize.models[modelToRemove.name];
23 }
24
25 getModel(against, options) {
26 options = _.defaults(options || {}, {
27 attribute: 'name'
28 });
29
30 return this.models.find(model => model[options.attribute] === against);
31 }
32
33 get all() {
34 return this.models;
35 }
36
37 /**
38 * Iterate over Models in an order suitable for e.g. creating tables.
39 * Will take foreign key constraints into account so that dependencies are visited before dependents.
40 *
41 * @param {Function} iterator method to execute on each model
42 * @param {Object} [options] iterator options
43 * @private
44 */
45 forEachModel(iterator, options) {
46 const models = {};
47 const sorter = new Toposort();
48 let sorted;
49 let dep;
50
51 options = _.defaults(options || {}, {
52 reverse: true
53 });
54
55 for (const model of this.models) {
56 let deps = [];
57 let tableName = model.getTableName();
58
59 if (_.isObject(tableName)) {
60 tableName = `${tableName.schema}.${tableName.tableName}`;
61 }
62
63 models[tableName] = model;
64
65 for (const attrName in model.rawAttributes) {
66 if (Object.prototype.hasOwnProperty.call(model.rawAttributes, attrName)) {
67 const attribute = model.rawAttributes[attrName];
68
69 if (attribute.references) {
70 dep = attribute.references.model;
71
72 if (_.isObject(dep)) {
73 dep = `${dep.schema}.${dep.tableName}`;
74 }
75
76 deps.push(dep);
77 }
78 }
79 }
80
81 deps = deps.filter(dep => tableName !== dep);
82
83 sorter.add(tableName, deps);
84 }
85
86 sorted = sorter.sort();
87 if (options.reverse) {
88 sorted = sorted.reverse();
89 }
90 for (const name of sorted) {
91 iterator(models[name], name);
92 }
93 }
94}
95
96module.exports = ModelManager;
97module.exports.ModelManager = ModelManager;
98module.exports.default = ModelManager;