antares/src/main/libs/AntaresConnector.js

292 lines
7.4 KiB
JavaScript
Raw Normal View History

2020-06-07 14:38:38 +02:00
'use strict';
2020-06-16 18:01:22 +02:00
import mysql from 'mysql';
2020-06-15 18:23:51 +02:00
import mssql from 'mssql';
2020-06-16 18:01:22 +02:00
// import pg from 'pg'; TODO: PostgreSQL
2020-06-07 14:38:38 +02:00
2020-06-14 19:02:07 +02:00
/**
* As Simple As Possible Query Builder
*
* @export
* @class AntaresConnector
*/
2020-06-07 14:38:38 +02:00
export class AntaresConnector {
2020-06-14 19:02:07 +02:00
/**
*Creates an instance of AntaresConnector.
* @param {Object} args connection params
* @memberof AntaresConnector
*/
2020-06-07 14:38:38 +02:00
constructor (args) {
2020-06-14 19:02:07 +02:00
this._client = args.client;
this._params = args.params;
this._poolSize = args.poolSize || false;
this._connection = null;
2020-07-24 17:34:39 +02:00
this._logger = args.logger || console.log;
2020-06-12 18:10:45 +02:00
2020-06-14 19:02:07 +02:00
this._queryDefaults = {
schema: '',
2020-06-12 18:10:45 +02:00
select: [],
from: '',
where: [],
groupBy: [],
orderBy: [],
2020-06-15 18:23:51 +02:00
limit: [],
2020-06-12 18:10:45 +02:00
join: [],
update: [],
2020-06-14 19:02:07 +02:00
insert: [],
2020-07-23 19:10:14 +02:00
delete: false
2020-06-12 18:10:45 +02:00
};
2020-06-14 19:02:07 +02:00
this._query = Object.assign({}, this._queryDefaults);
2020-06-07 14:38:38 +02:00
}
2020-06-14 19:02:07 +02:00
_reducer (acc, curr) {
const type = typeof curr;
switch (type) {
case 'number':
case 'string':
return [...acc, curr];
case 'object':
if (Array.isArray(curr))
return [...acc, ...curr];
else {
const clausoles = [];
for (const key in curr)
clausoles.push(`${key} ${curr[key]}`);
return clausoles;
}
}
}
2020-06-16 18:01:22 +02:00
/**
* Resets the query object after a query
*
* @memberof AntaresConnector
*/
2020-06-14 19:02:07 +02:00
_resetQuery () {
this._query = Object.assign({}, this._queryDefaults);
}
/**
* @memberof AntaresConnector
*/
2020-06-15 18:23:51 +02:00
async connect () {
2020-06-14 19:02:07 +02:00
switch (this._client) {
2020-06-07 14:38:38 +02:00
case 'maria':
case 'mysql':
2020-06-20 21:58:57 +02:00
if (!this._poolSize)
this._connection = mysql.createConnection(this._params);
2020-06-16 18:01:22 +02:00
else
this._connection = mysql.createPool({ ...this._params, connectionLimit: this._poolSize });
2020-06-07 14:38:38 +02:00
break;
2020-06-15 18:23:51 +02:00
case 'mssql': {
const mssqlParams = {
user: this._params.user,
password: this._params.password,
server: this._params.host
};
this._connection = await mssql.connect(mssqlParams);
}
break;
2020-06-07 14:38:38 +02:00
default:
break;
}
}
2020-06-14 19:02:07 +02:00
schema (schema) {
this._query.schema = schema;
return this;
}
2020-06-12 18:10:45 +02:00
2020-06-14 19:02:07 +02:00
select (...args) {
this._query.select = [...this._query.select, ...args];
return this;
}
2020-06-12 18:10:45 +02:00
2020-06-14 19:02:07 +02:00
from (table) {
this._query.from = table;
return this;
}
2020-07-23 19:10:14 +02:00
delete (table) {
this._query.delete = true;
this.from(table);
return this;
}
2020-06-14 19:02:07 +02:00
where (...args) {
this._query.where = [...this._query.where, ...args];
return this;
}
groupBy (...args) {
this._query.groupBy = [...this._query.groupBy, ...args];
return this;
}
orderBy (...args) {
this._query.orderBy = [...this._query.orderBy, ...args];
return this;
}
2020-06-15 18:23:51 +02:00
limit (...args) {
this._query.limit = args;
return this;
}
2020-06-16 18:01:22 +02:00
use (schema) {
let sql;
switch (this._client) {
case 'maria':
case 'mysql':
sql = `USE \`${schema}\``;
break;
case 'mssql':
sql = `USE "${schema}"`;
break;
default:
break;
}
return this.raw(sql);
}
2020-07-23 19:10:14 +02:00
/**
* @param {String | Array} args field = value
* @returns
* @memberof AntaresConnector
*/
2020-06-27 15:14:08 +02:00
update (...args) {
this._query.update = [...this._query.update, ...args];
return this;
}
2020-06-15 18:23:51 +02:00
/**
* @returns {string} SQL string
* @memberof AntaresConnector
*/
getSQL () {
2020-06-16 18:01:22 +02:00
// SELECT
2020-06-14 19:02:07 +02:00
const selectArray = this._query.select.reduce(this._reducer, []);
2020-06-27 15:14:08 +02:00
let selectRaw = '';
if (selectArray.length) {
switch (this._client) {
case 'maria':
case 'mysql':
selectRaw = selectArray.length ? `SELECT ${selectArray.join(', ')} ` : 'SELECT * ';
break;
case 'mssql': {
const topRaw = this._query.limit.length ? ` TOP (${this._query.limit[0]}) ` : '';
selectRaw = selectArray.length ? `SELECT${topRaw} ${selectArray.join(', ')} ` : 'SELECT * ';
}
break;
default:
break;
2020-06-15 18:23:51 +02:00
}
}
2020-06-16 18:01:22 +02:00
// FROM
2020-06-27 15:14:08 +02:00
let fromRaw = '';
2020-07-23 19:10:14 +02:00
if (!this._query.update.length && !!this._query.from)
2020-06-27 15:14:08 +02:00
fromRaw = 'FROM';
2020-06-15 18:23:51 +02:00
switch (this._client) {
case 'maria':
case 'mysql':
2020-06-27 15:14:08 +02:00
fromRaw += this._query.from ? ` ${this._query.schema ? `\`${this._query.schema}\`.` : ''}\`${this._query.from}\` ` : '';
2020-06-15 18:23:51 +02:00
break;
case 'mssql':
2020-06-27 15:14:08 +02:00
fromRaw += this._query.from ? ` ${this._query.schema ? `${this._query.schema}.` : ''}${this._query.from} ` : '';
2020-06-15 18:23:51 +02:00
break;
default:
break;
}
2020-06-14 19:02:07 +02:00
const whereArray = this._query.where.reduce(this._reducer, []);
2020-06-15 18:23:51 +02:00
const whereRaw = whereArray.length ? `WHERE ${whereArray.join(' AND ')} ` : '';
2020-06-27 15:14:08 +02:00
const updateArray = this._query.update.reduce(this._reducer, []);
const updateRaw = updateArray.length ? `SET ${updateArray.join(', ')} ` : '';
2020-06-14 19:02:07 +02:00
const groupByArray = this._query.groupBy.reduce(this._reducer, []);
2020-06-15 18:23:51 +02:00
const groupByRaw = groupByArray.length ? `GROUP BY ${groupByArray.join(', ')} ` : '';
2020-06-27 15:14:08 +02:00
2020-06-14 19:02:07 +02:00
const orderByArray = this._query.orderBy.reduce(this._reducer, []);
2020-06-15 18:23:51 +02:00
const orderByRaw = orderByArray.length ? `ORDER BY ${orderByArray.join(', ')} ` : '';
2020-06-14 19:02:07 +02:00
2020-06-16 18:01:22 +02:00
// LIMIT
2020-06-15 18:23:51 +02:00
let limitRaw;
switch (this._client) {
case 'maria':
case 'mysql':
limitRaw = this._query.limit.length ? `LIMIT ${this._query.limit.join(', ')} ` : '';
break;
case 'mssql':
limitRaw = '';
break;
default:
break;
}
2020-07-23 19:10:14 +02:00
return `${selectRaw}${updateRaw ? 'UPDATE' : ''}${this._query.delete ? 'DELETE ' : ''}${fromRaw}${updateRaw}${whereRaw}${groupByRaw}${orderByRaw}${limitRaw}`;
2020-06-14 19:02:07 +02:00
}
2020-06-15 18:23:51 +02:00
/**
* @returns {Promise}
* @memberof AntaresConnector
*/
async run () {
const rawQuery = this.getSQL();
2020-06-14 19:02:07 +02:00
this._resetQuery();
return this.raw(rawQuery);
}
2020-06-12 18:10:45 +02:00
2020-06-14 19:02:07 +02:00
/**
2020-06-15 18:23:51 +02:00
* @param {string} sql raw SQL query
2020-06-14 19:02:07 +02:00
* @returns {Promise}
* @memberof AntaresConnector
*/
2020-06-07 14:38:38 +02:00
async raw (sql) {
2020-07-24 17:34:39 +02:00
if (process.env.NODE_ENV === 'development') this._logger(sql);
2020-06-16 18:01:22 +02:00
2020-06-28 15:31:16 +02:00
switch (this._client) { // TODO: uniform fields with every client type, needed table name and fields array
2020-06-07 14:38:38 +02:00
case 'maria':
case 'mysql': {
2020-06-16 18:01:22 +02:00
const { rows, fields } = await new Promise((resolve, reject) => {
this._connection.query(sql, (err, rows, fields) => {
if (err)
reject(err);
else
resolve({ rows, fields });
});
});
2020-06-07 14:38:38 +02:00
return { rows, fields };
}
2020-06-15 18:23:51 +02:00
case 'mssql': {
const results = await this._connection.request().query(sql);
2020-06-16 18:01:22 +02:00
return { rows: results.recordsets[0] };// TODO: fields
2020-06-15 18:23:51 +02:00
}
2020-06-07 14:38:38 +02:00
default:
break;
}
}
2020-06-14 19:02:07 +02:00
/**
* @memberof AntaresConnector
*/
2020-06-07 14:38:38 +02:00
destroy () {
2020-06-14 19:02:07 +02:00
switch (this._client) {
2020-06-07 14:38:38 +02:00
case 'maria':
2020-06-15 18:23:51 +02:00
case 'mysql':
2020-06-14 19:02:07 +02:00
this._connection.end();
2020-06-07 14:38:38 +02:00
break;
2020-06-15 18:23:51 +02:00
case 'mssql':
this._connection.close();
break;
2020-06-07 14:38:38 +02:00
default:
break;
}
}
}