Skip to content

Instantly share code, notes, and snippets.

@andrewgeorgemitchell
Last active March 24, 2019 22:39
Show Gist options
  • Save andrewgeorgemitchell/ca671ea044529fbe1d35224e7cbb5f1f to your computer and use it in GitHub Desktop.
Save andrewgeorgemitchell/ca671ea044529fbe1d35224e7cbb5f1f to your computer and use it in GitHub Desktop.
const { Client } = require('pg');
const { pg } = require('../../config');
module.exports = {
getAll: async (table) => {
try {
const db = new Client(pg);
await db.connect();
const query = `SELECT * FROM ${table}`;
const results = await db.query(query);
db.end();
return results.rows;
} catch (error) {
return error;
}
},
getOne: async (table, id) => {
const db = new Client(pg);
await db.connect();
const query = `
SELECT * FROM ${table}
WHERE ${table}.id = ${db.escape(id)}
`;
const results = await db.query(query);
db.end();
return results;
},
create: async (table, data) => {
try {
const db = new Client(pg);
await db.connect();
const keys = Object.keys(data);
const values = keys.map(value => data[value]);
const placeholders = values.map((value, index) => `$${index + 1}`);
const query = `
INSERT INTO ${table}(${keys.join(',')})
VALUES(${placeholders.join(',')})
RETURNING *
`;
const results = await db.query(query, values);
db.end();
return results;
} catch (error) {
return error;
}
},
update: async (table, id, data) => {
const db = new Client(pg);
await db.connect();
const keys = Object.keys(data);
let setStr = '';
for (let i = 0; i < keys.length; i += 1) {
let newStr = `${keys[i]} = ${db.escape(data[keys[i]])}`;
if (i !== keys.length - 1) {
newStr = `${newStr},`;
}
setStr = `${setStr} ${newStr}`;
}
const query = `
INSERT ${table}
SET ${setStr}
WHERE ${table}.id = ${db.escape(id)}
`;
const results = await db.query(query);
db.end();
return results;
},
delete: async (table, id) => {
const db = new Client(pg);
await db.connect();
const query = `
DELETE ${table}
WHERE ${table}.id = ${db.escape(id)}
`;
const results = await db.query(query);
db.end();
return results;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment