UNPKG

legendaryjs

Version:

LegendaryJS – The ultimate backend framework for speed, power, and simplicity.

62 lines (56 loc) 2.08 kB
const { connections } = require('./index'); async function queryDB(db, action, options = {}) { switch (db) { case 'mongo': return handleMongo(action, options); case 'postgres': return handlePostgres(action, options); case 'mysql': return handleMySQL(action, options); default: throw new Error(`Unknown DB engine: ${db}`); } } // MongoDB async function handleMongo(action, { model, filter = {}, data = {} }) { const Model = require(`./models/${model}`); switch (action) { case 'find': return await Model.find(filter); case 'findOne': return await Model.findOne(filter); case 'create': return await Model.create(data); case 'update': return await Model.updateMany(filter, { $set: data }); case 'delete': return await Model.deleteMany(filter); } } // PostgreSQL async function handlePostgres(action, { table, filter = {}, data = {} }) { const pool = connections.postgres; let query = '', values = []; switch (action) { case 'find': const where = Object.keys(filter).map((k, i) => `${k} = $${i + 1}`).join(' AND '); values = Object.values(filter); query = `SELECT * FROM ${table} ${where ? 'WHERE ' + where : ''}`; return (await pool.query(query, values)).rows; case 'create': const cols = Object.keys(data); values = Object.values(data); const placeholders = cols.map((_, i) => `$${i + 1}`).join(', '); query = `INSERT INTO ${table} (${cols.join(', ')}) VALUES (${placeholders}) RETURNING *`; return (await pool.query(query, values)).rows; // (other actions can be added similarly) } } // MySQL async function handleMySQL(action, { table, filter = {}, data = {} }) { const conn = connections.mysql; switch (action) { case 'find': let [rows] = await conn.query(`SELECT * FROM ${table}`); return rows; case 'create': let [result] = await conn.query(`INSERT INTO ${table} SET ?`, data); return result; } } module.exports = { queryDB };