This repository has been archived by the owner on Dec 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
68 lines (56 loc) · 1.96 KB
/
index.js
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
const Sequelize = require('sequelize');
const Pick = require('object.pick');
const Path = require('path');
let _config = {};
let _config_path = '.';
let _sequelize = {};
let _models = new Proxy({}, {
get: (target, prop, receiver) => (prop in target ? true : autoload(prop)) && target[prop]
});
const read = function(path) {
if(Path.normalize(path) !== Path.resolve(path)) {
const callerFileName = (module.parent || {}).filename || __filename;
const callerPath = Path.dirname(callerFileName);
path = Path.resolve(callerPath, path);
}
return path;
};
const load = function(config = '') {
config = read(config);
_config = require(config);
_config_path = config;
_sequelize = new Sequelize(
_config.server.database,
_config.server.username,
_config.server.password,
Pick(_config.server, ['host', 'dialect', 'define'])
);
_models = new Proxy({}, {
get: (target, prop, receiver) => (prop in target ? true : autoload(prop)) && target[prop]
});
_prototype.sequelize = _sequelize;
_prototype.config = _config;
_prototype.models = _models;
};
const autoload = function(models = []) {
if(typeof models === 'string' && models !== '') {
if(models in _config.models.tables) {
let filename = _config.models.tables[models];
let path = Path.resolve(_config_path, _config.models.root, `${filename}.js`);
_models[models] = _sequelize.import(read(path));
}
} else if(typeof models === 'object' && Array.isArray(models) && models.length > 0) {
for(let model of models)
autoload(model);
} else {
return false;
}
return true;
};
let _prototype = {};
_prototype.sequelize = _sequelize;
_prototype.config = _config;
_prototype.models = _models;
_prototype.load = load;
_prototype.Op = Sequelize.Op;
module.exports = _prototype;