Skip to content

Instantly share code, notes, and snippets.

@king1600
Created May 14, 2018 02:28
Show Gist options
  • Save king1600/124b9a584d9175b8cb14a91b210ada94 to your computer and use it in GitHub Desktop.
Save king1600/124b9a584d9175b8cb14a91b210ada94 to your computer and use it in GitHub Desktop.
const Sql = require('mysql');
const Express = require('express');
const app = Express();
const port = process.argv[6] || '8080';
const database = process.argv[5];
const pool = Sql.createPool({
database: database,
connectionLimit: 10,
host: process.argv[2],
user: process.argv[3],
password: process.argv[4]
});
async function startServer() {
app.use(Express.json());
await GenerateRoutes();
app.listen(parseInt(port));
}
async function Query(...args) {
return new Promise((resolve, reject) => {
args.push((error, results, fields) => {
if (error) return resolve(error);
resolve([results, fields])
});
pool.query(...args);
});
}
function WHERE(json) {
return Object.keys(json)
.map(key => `\`${key}\` = ?`)
.join(' ');
}
async function GenerateRoutes() {
return new Promise(async (resolve, reject) => {
const tables = (await Query('show tables'))[0];
let routesGenerated = tables.length;
tables.forEach(async tableResult => {
const id = {};
const table = tableResult['Tables_in_' + database];
const columns = (await Query(`describe ${table}`))[0]
.filter(result => !result.Extra.length)
.map(result => result.Field);
const placeholders = '(' + columns.map(_ => '?').join(',') + ')';
const columnTuple = '(' + columns.map(column => `\`${column}\``).join(',') + ')';
id[(await Query(`show keys from ${table} where Key_name = 'PRIMARY'`))[0][0].Column_name] = 0;
app.get(`/${table}`, async (req, resp) =>
resp.send((await Query(`SELECT * FROM ${table}`)[0])));
app.get(`/${table}/:id`, async (req, resp) =>
resp.send((await Query(`SELECT * FROM ${table} ${WHERE(id)}`, req.params.id)[0])));
app.delete(`/${table}/:id`, async (req, resp) =>
resp.send((await Query(`DELETE FROM ${table} ${WHERE(id)}`, req.params.id)[0])));
app.put(`/${table}/:id`, async (req, resp) => {
const keys = Object.keys(req.body).filter(key => columns.includes(key));
const cols = keys.map(key => `\`${key}\` = ?`).join(',');
const values = keys.map(key => req.body[key]);
values.push(req.params.id);
resp.send((await Query(`UPDATE ${table} SET ${key} ${WHERE(id)}`, values))[0]);
});
app.post(`/${table}`, async (req, resp) => {
const keys = Object.keys(req.body)
.filter(key => columns.includes(key))
const values = keys.map(key => req.body[key]);
await Query(`INSERT INTO ${table} (${keys.join(',')}) VALUES (${keys.map(_ => '?').join(',')})`, values);
resp.end();
});
if (--routesGenerated === 0)
resolve();
});
});
}
startServer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment