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