connects to postgres, get and post function
This commit is contained in:
2
config.env
Normal file
2
config.env
Normal file
@@ -0,0 +1,2 @@
|
||||
PORT=8088
|
||||
CONNECTION=postgres://mikayladobson@localhost/ecommerce_041822
|
||||
9
db/Client.js
Normal file
9
db/Client.js
Normal file
@@ -0,0 +1,9 @@
|
||||
const { Client } = require('pg');
|
||||
require('dotenv').config({ path: '../config.env' });
|
||||
|
||||
const connectionString = 'postgres://mikayladobson@localhost/ecommerce_041822';
|
||||
const client = () => {
|
||||
return new Client(connectionString);
|
||||
}
|
||||
|
||||
module.exports = client;
|
||||
@@ -1,8 +1,41 @@
|
||||
const express = require('express');
|
||||
const userRouter = express.Router();
|
||||
|
||||
userRouter.route('/users').get((req, res) => {
|
||||
res.send('users router');
|
||||
const client = require('../db/Client');
|
||||
|
||||
userRouter.route('/users').get(async (req, res) => {
|
||||
const newClient = client();
|
||||
|
||||
try {
|
||||
await newClient.connect();
|
||||
console.log('Connection successful.');
|
||||
|
||||
const results = await newClient.query("SELECT * FROM users");
|
||||
res.send(results.rows);
|
||||
} catch(e) {
|
||||
console.log(e);
|
||||
} finally {
|
||||
await newClient.end();
|
||||
console.log("Client disconnected.");
|
||||
}
|
||||
});
|
||||
|
||||
userRouter.route('/users').post(async (req, res) => {
|
||||
const body = ['Mikayla'];
|
||||
const newClient = client();
|
||||
|
||||
try {
|
||||
await newClient.connect()
|
||||
.then(console.log("Connection successful."));
|
||||
|
||||
await newClient.query(("INSERT INTO users (name) VALUES ('mikayla')"))
|
||||
.then(res.sendStatus(204));
|
||||
} catch(e) {
|
||||
console.log(e);
|
||||
} finally {
|
||||
await newClient.end()
|
||||
.then(console.log("Client disconnected."));
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = userRouter;
|
||||
Reference in New Issue
Block a user