randia-api-builder
Version:
Samll API Builder
107 lines (93 loc) • 2.74 kB
JavaScript
/**
* Created by badhrc on 7/10/17.
*/
const config = require('./config.json')
// Imports
const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
let db = null;
if (config.dbs[config.selectedDB].name = "PostgresSQL")
db = require('./db');
else
db = require('mysql');
// App and Config
const app = express();
//Middlewares
app.use(morgan('combined'));
app.use(cors());
module.exports.launch = function () {
app.listen(config.APP_PORT, function () {
"use strict";
console.log("Listening on *:" + config.APP_PORT);
})
}
/**
*
* @param METHOD
* @param ENDPOINT
* @param handler
*/
module.exports.addRoute = function (METHOD, ENDPOINT, handler) {
"use strict";
if (typeof handler !== "function")
throw new Error('handler must be a function');
switch (METHOD) {
case "GET" :
app.get(ENDPOINT, handler);
break;
case "POST" :
app.post(ENDPOINT, handler);
break;
case "PUT" :
app.put(ENDPOINT, handler);
break;
case "DELETE" :
app.delete(ENDPOINT, handler);
break;
default :
console.error("");
throw new Error("You must use GET|POST|PUT|DELETE");
}
console.log(`You added a ${METHOD} Method`);
}
/**
* Get the users from the TABLE_USER set in config.json
* @param {function} callback that receive results
*/
module.exports.getUsers = function (callback) {
"use strict";
db.query("SELECT * FROM " + config.USER_TABLE_NAME, [], function (err, res) {
"use strict";
if (err) callback(err);
else
callback(null, res.rows);
});
};
/**
* Insert Document into DATABASE
* @param {string} TABLE_NAME represents the table of inner data
* @param {Array} document to uplaod
* @param {function} handler the callback function
*/
module.exports.insertDocument = function (TABLE_NAME, document, handler) {
"use strict";
db.query(`INSERT INTO ${TABLE_NAME} VALUES` + getNumberOfParamsInInsertFunction(document), document, handler);
};
module.exports.deleteDocument = function(TABLE_NAME, idName, idDocument,handler) {
"use strict";
db.query(`DELETE FROM ${TABLE_NAME} WHERE ${idName}=$1`, idDocument, handler);
}
function getNumberOfParamsInInsertFunction(document) {
"use strict";
let query_string = "(";
for (let i =0; i<=document.length;i++) {
if (document[i] == 'DEFAULT'){
query_string += `default, `;
document.splice(i,1);
}
else
query_string += `$${i},`;
}
return query_string.substr(0, query_string.length - 1) + ")";
}