myt/lib/server.js

72 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-12-02 07:35:26 +00:00
2020-12-04 09:15:29 +00:00
const mysql = require('mysql2/promise');
2020-12-02 07:35:26 +00:00
module.exports = class Server {
2020-12-04 09:15:29 +00:00
constructor(ct, dbConfig) {
2020-12-02 07:35:26 +00:00
Object.assign(this, {
2020-12-04 09:15:29 +00:00
ct,
dbConfig
2020-12-02 07:35:26 +00:00
});
}
wait() {
return new Promise((resolve, reject) => {
const mysql = require('mysql2');
let interval = 100;
let elapsedTime = 0;
let maxInterval = 4 * 60 * 1000;
2020-12-04 09:15:29 +00:00
const dbConfig = this.dbConfig;
2020-12-02 07:35:26 +00:00
let myConf = {
2020-12-04 09:15:29 +00:00
user: dbConfig.user,
password: dbConfig.password,
host: dbConfig.host,
port: dbConfig.port
2020-12-02 07:35:26 +00:00
};
2020-12-04 09:15:29 +00:00
console.log('Waiting for MySQL init process...');
2020-12-02 07:35:26 +00:00
async function checker() {
elapsedTime += interval;
let status;
try {
2020-12-04 09:15:29 +00:00
status = await this.ct.inspect({
format: '{{json .State.Status}}'
2020-12-02 07:35:26 +00:00
});
} catch (err) {
return reject(new Error(err.message));
}
if (status === 'exited')
return reject(new Error('Docker exited, please see the docker logs for more info'));
2020-12-04 09:15:29 +00:00
const conn = mysql.createConnection(myConf);
2020-12-02 07:35:26 +00:00
conn.on('error', () => {});
conn.connect(err => {
conn.destroy();
if (!err) {
2020-12-04 09:15:29 +00:00
console.log('MySQL process ready.');
2020-12-02 07:35:26 +00:00
return resolve();
}
if (elapsedTime >= maxInterval)
reject(new Error(`MySQL not initialized whithin ${elapsedTime / 1000} secs`));
else
setTimeout(bindedChecker, interval);
});
}
2020-12-04 09:15:29 +00:00
const bindedChecker = checker.bind(this);
2020-12-02 07:35:26 +00:00
bindedChecker();
});
}
async rm() {
try {
2020-12-04 09:15:29 +00:00
await this.ct.stop();
await this.ct.rm({volumes: true});
2020-12-02 07:35:26 +00:00
} catch (e) {}
}
};