refactored for pg pool

This commit is contained in:
Mikayla Dobson
2022-07-05 11:59:37 -05:00
parent f54b4fc5d6
commit f1d964b092
8 changed files with 85 additions and 87 deletions

View File

@@ -1,38 +1,41 @@
const express = require('express');
const userRouter = express.Router();
const client = require('../db/Client');
// const client = require('../db/Client');
const { connect } = require('../db/Pool');
// get a list of all users, or a single user matching an email passed in as a query param
userRouter.route('/').get(async (req, res) => {
const newClient = client();
const { email } = req.query;
const client = await connect()
.then(console.log('Connection successful.'))
.catch(e => console.log(e));
if (!email) {
try {
await newClient.connect()
.then(console.log('Connection successful.'));
const results = await newClient.query("SELECT * FROM users");
res.send(results.rows);
await client.query("BEGIN");
const results = await client.query("SELECT * FROM users");
await client.query("COMMIT");
if (results) res.send(results.rows);
} catch(e) {
console.log(e);
await client.query('ROLLBACK');
throw new Error(e);
} finally {
await newClient.end();
await client.release();
console.log("Client disconnected.");
}
} else {
try {
await newClient.connect()
.then(console.log("Connection successful."));
const result = await newClient.query(("SELECT * FROM users WHERE email = ($1)"), [email])
res.send(result.rows);
await client.query("BEGIN");
const result = await client.query(("SELECT * FROM users WHERE email = ($1)"), [email])
await client.query("COMMIT");
if (result) res.send(result.rows);
} catch(e) {
console.log(e);
await client.query('ROLLBACK');
throw new Error(e);
} finally {
await newClient.end()
.then(console.log("Client disconnected."));
await client.release();
console.log("Client disconnected.");
}
}
});
@@ -40,19 +43,21 @@ userRouter.route('/').get(async (req, res) => {
// post a new user to the database
userRouter.route('/').post(async (req, res) => {
const { name, email } = req.body;
const newClient = client();
const client = await connect()
.then(console.log('Connection successful.'));
const input = "INSERT INTO users (name, email) VALUES ($1, $2)";
try {
await newClient.connect()
.then(console.log("Connection successful."));
await newClient.query(("INSERT INTO users (name, email) VALUES ($1, $2)"), [name, email])
.then(res.sendStatus(204));
await client.query("BEGIN");
await client.query(input, [name, email]);
await client.query("COMMIT");
res.sendStatus(200);
} catch(e) {
console.log(e);
await client.query('ROLLBACK');
throw new Error(e);
} finally {
await newClient.end()
.then(console.log("Client disconnected."));
await client.release();
console.log("Client disconnected.");
}
});