This repository has been archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (80 loc) · 3 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* globals process */
const Sequelize = require('sequelize');
const { findPlugins, createRegisterPlugins } = require('./utils/plugins');
let retries = 0;
const ORM = {
async init(config) {
const dbConfig = config.orm && config.orm.db ? config.orm.db : config.db;
const retryInterval = config.orm.retryInterval ? config.orm.retryInterval * 1000 : 3000;
let configuredPlugins = {};
if (config.general && config.general.localPluginRoot && config.plugins) {
configuredPlugins = await findPlugins(config.general.localPluginRoot, config.plugins);
}
/**
* attempts to initialize the ORM. if it fails and
* `config.orm.retry`` is true, it will retry connecting after
* 10 seconds.
*/
async function connect() {
const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
host: dbConfig.host,
port: dbConfig.port,
dialect: dbConfig.dialect,
logging: process.env.DEV ? s => process.stdout.write(s + '\n') : false,
define: {
timestamps: true,
updatedAt: false,
underscored: true
}
});
try {
if (!config.orm.skipTableTest) {
await sequelize.query('select id from chart limit 1');
}
ORM.db = sequelize;
ORM.db.Op = Sequelize.Op;
ORM.db.Sequelize = Sequelize;
ORM.token_salt = config.secure_auth_salt || '';
ORM.chartIdSalt = config.orm.chartIdSalt;
ORM.hashPublishing = config.orm.hashPublishing;
ORM.plugins = configuredPlugins;
ORM.registerPlugins = createRegisterPlugins(ORM, configuredPlugins);
} catch (err) {
if (err.name.substr(0, 9) === 'Sequelize' && config.orm && config.orm.retry) {
console.warn(err.message);
console.warn(
`database is not ready, yet. retrying in ${retryInterval / 1000} seconds...`
);
if (!config.orm.retryLimit || retries < config.orm.retryLimit) {
retries++;
await wait(connect, retryInterval);
} else {
throw err;
}
} else {
throw err;
}
}
return ORM;
}
return connect();
},
db: {
define() {
console.error('you need to initialize the database first!');
process.exit(-1);
}
}
};
module.exports = ORM;
function wait(f, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
resolve(f());
} catch (error) {
reject(error);
}
}, ms);
});
}