Commit ab80b552 authored by Milan Wikarski's avatar Milan Wikarski 🕳

Initial commit

parents
/**
* @module db
*
* @private @method _getWhere
* @description
* Parses the where parameter and returns query substring
* @param {Object, String} where
*
* @private @method _getLimit
* @description
* Parses the limit parameter and returns query substring
* @param {Number} limit
*
* @private @method _getReturning
* @description
* Parses the returning parameter and returns query substring
* @param {Array, String} returning
*
* @private @method _sendResponse
* @description
* Executes query with given data
* Transforms object keys to camel case
* @param {String} q - query to be executed
* @param {Array} data = [] - data to replace placeholders in query
*
* @public @method query
* @description
* Executes query
* @param {String} q - The query to be executed
* @param {Array} data = [] - data to replace placeholders in query
*
* @public @method tableExists
* @description
* Determines wether a table or a view with such name exists
* @param {String} tableName - the name of the table
*/
// NEMAZS ANI ZA BOHA 🖕
const { Pool } = require('pg');
const { snake2camel } = require('./utils/case');
const _db = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_USER,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT
});
class DB {
_db = null;
constructor(params) {
this._db = new Pool(params);
}
_getWhere(where) {
if (where instanceof Object && Object.entries(where).length) {
return (
' WHERE ' +
Object.entries(where)
.map(([key, value]) =>
value instanceof Object
? `"${value.key}" ${value.operator} '${value.value}'`
: `"${key}" = '${value}'`
)
.join(' AND ')
);
} else if (typeof where === 'string' && where.length) {
return ' WHERE ' + where;
}
return '';
}
_getLimit(limit) {
if (!isNaN(Number(limit)) && limit != null) {
return ' LIMIT ' + limit;
}
return '';
}
_getReturning(returning) {
if (typeof returning === 'string') {
return ` RETURNING ${returning}`;
} else if (Array.isArray(returning)) {
return ` RETURNING ${returning.join(',')}`;
}
return '';
}
_sendResponse(q, data = []) {
return new Promise((resolve, reject) => {
_db.query(q, data, (err, res) =>
err ? reject(err) : resolve(res.rows.map(record => snake2camel(record)))
);
});
}
query(q, data = []) {
return this._sendResponse(q, data);
}
tableExists(tableName) {
return _db.query(
'SELECT EXISTS( SELECT 1 FROM information_schema.tables WHERE table_name=$1 )',
[tableName],
(err, res) => (err ? reject(err) : resolve(res.rows[0][0]))
);
}
select(tableName, columns = '*', where = null, limit = null) {
let q;
if (typeof columns === 'string') {
q = `SELECT ${columns} FROM ${tableName}`;
} else if (Array.isArray(columns)) {
q = `SELECT ${columns.join(',')} FROM ${tableName}`;
} else {
throw new TypeError(
columns +
' is of invalid type; valid types are String and Array of String'
);
}
q += this._getWhere(where);
q += this._getLimit(limit);
return this._sendResponse(q);
}
insert(tableName, data, returning) {
let keys = Object.keys(Array.isArray(data) ? data[0] : data).map(
key => `"${key}"`
);
let values = Array.isArray(data)
? [].concat(...data.map(record => Object.values(record)))
: Object.values(data);
let placeholders;
if (Array.isArray(data)) {
let index = 1;
placeholders =
'VALUES ' +
data
.map(
() =>
`(${Array.from({ length: keys.length }, () => '$' + index++)})`
)
.join(',');
} else {
placeholders = `VALUES(${Array.from(
{ length: keys.length },
(record, index) => '$' + (index + 1)
)})`;
}
keys = `(${keys.join(',')})`;
let q = `INSERT INTO ${tableName} ${keys} ${placeholders}`;
q += this._getReturning(returning);
return this._sendResponse(q, values);
}
delete(tableName, where = null, returning = null) {
let q = `DELETE FROM ${tableName}`;
q += this._getWhere(where);
q += this._getReturning(returning);
return this._sendResponse(q);
}
update(tableName, columnNames, data, conditionColumn, conditionData) {
// Setup static beginning of query
var q = [`UPDATE ${tableName}`];
q.push('SET');
// Create another array storing each set command
// and assigning a number value for parameterized q
var set = [];
Object.values(columnNames).forEach(function(key, i) {
set.push(key + ' = ($' + (i + 1) + ')');
});
q.push(set.join(', '));
// Add the WHERE statement to look up by id
q.push(`WHERE ${conditionColumn} = '${conditionData}';`);
q = q.join(' ');
return this._sendResponse(q, data);
}
}
module.exports = DB;
{
"name": "@creanet/db",
"version": "1.0.0",
"description": "Used for communication between NodeJS and PostgreSQL",
"main": "index.js",
"scripts": {
"test": "node tests/run-tests.js"
},
"repository": {
"type": "git",
"url": "git@gitlab.creanet.sk:kero/db-js.git"
},
"keywords": [
"PostgreSQL",
"Database",
"DB",
"NodeJS"
],
"author": "Milan Wikarski,Marcel Odumorek",
"license": "ISC"
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment