Created
December 13, 2018 00:32
-
-
Save kselax/6628daf214113fa1fb63510b4cf402b1 to your computer and use it in GitHub Desktop.
DB class to work with the database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const fs = require('fs'); | |
const Table = require('./Table'); | |
const Log = require('../../model/Log'); | |
class DB { | |
constructor() { | |
this.pool = null; | |
this.tablesNameArray = []; | |
} | |
setOptions(options, driverDb) { | |
this.pool = driverDb.createPool(options); | |
} | |
connection() { | |
return this.pool.getConnection() | |
.then(() => { | |
return this.afterConnection() | |
}); | |
} | |
afterConnection() { | |
// Очищаем таблицы Sockets | |
return new Promise((resolve, reject) => { | |
this.Sockets.deleteAll(); | |
resolve(null); | |
}); | |
} | |
addTable(tablesNameArray) { | |
this.tablesNameArray = this.tablesNameArray.concat(tablesNameArray); | |
this.addTableInstance(tablesNameArray); | |
} | |
addTableInstance(tablesNameArray) { | |
// Добавляем объекты для работы с таблицами | |
tablesNameArray.forEach((tableName) => { | |
if (tableName !== 'Table' && tableName !== 'DB') { | |
fs.stat(`${__dirname}/${tableName}.js`, (err, stats) => { | |
if (!err && stats.isFile()) { | |
const extTable = require(`./${tableName}`); | |
this[tableName] = new extTable(tableName, this.query.bind(this)); | |
} else { | |
this[tableName] = new Table(tableName, this.query.bind(this)); | |
} | |
}); | |
} | |
}); | |
} | |
errorLog(err) { | |
if (err) { | |
console.warn('Ошибка запроса БД'); | |
if (Object.prototype.hasOwnProperty.call(this, 'Log')) { | |
const item = new Log(err, 'error', 'database'); | |
this.Log.insertOne(item); | |
} else { | |
console.warn('Недоступна таблица Log'); | |
} | |
} | |
} | |
query(queryStr, data) { | |
console.log('Query: ', queryStr); | |
console.log('Query fields: ', data); | |
return new Promise((resolve, reject) => { | |
this.pool.query(queryStr, data) | |
.then((result) => { | |
resolve(...result); | |
}) | |
.catch(err => reject(err)); | |
}); | |
} | |
} | |
module.exports = new DB(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment