SHARE
TWEET

Untitled

a guest Mar 21st, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require("express");
  2. const { Pool } = require("pg");
  3. const dotenv = require("dotenv");
  4.  
  5. dotenv.config();
  6.  
  7. // Conncet to DATABASE_URL from .env file
  8. const pool = new Pool({
  9.   connectionString: process.env.DATABASE_URL
  10. });
  11.  
  12. pool.on("connect", () => {
  13.   console.log("connected to the db");
  14. });
  15.  
  16. const app = express();
  17.  
  18. app.use(express.json());
  19.  
  20. // Get route
  21. app.get("/api", (req, res) => {
  22.   // pg connect
  23.   pool.connect((err, client, done) => {
  24.     client.query('SELECT * FROM activities')
  25.     .then(res => console.log('Success..'))
  26.     .catch(err => console.error(err.stack))
  27.  
  28.     done();
  29.     res.send(200);
  30.   });
  31.   // pool shutdown
  32.   pool.end();
  33.  
  34.   // return res.status(200).send({ message: "Congratulations! You connected to postgres" });
  35. });
  36.  
  37. // /api POST
  38. app.post('/api/add', (req, res) => {
  39.   // pg connect
  40.   pool.connect((err, client, done) => {
  41.     client.query('INSERT INTO activities(activity, undone, done) VALUES("laundry", "yes", "no"')
  42.     .then(res => console.log('Items added..'))
  43.     .catch(err => console.error(err.stack))
  44.  
  45.     done();
  46.     res.redirect('/api');
  47.   });
  48.   // pool shutdown
  49.   pool.end();
  50.  
  51.   return res.status(200).send({ message: "Congratulations! made a post request to postgres" });
  52. });
  53.  
  54. //  /api DELETE
  55. app.delete('/delete/:id', (req, res) => {
  56.   // pg connect
  57.   pool.connect((err, client, done) => {
  58.     client.query('DELETE FROM activities WHERE done = "yes"')
  59.     .then(res => console.log('Items delted..'))
  60.     .catch(err => console.error(err.stack))
  61.  
  62.     done();
  63.     res.send(200);
  64.   });
  65. // pool shutdown
  66. pool.end();
  67. });
  68.  
  69. // api/ edit
  70. app.post('/api/edit', (req, res) => {
  71.   // pg connect
  72.   pool.connect((err, client, done) => {
  73.     client.query('UPDATE activites SET activity = Cook , undone = no, done = yes WHERE activity = "laundry"')
  74.     .then(res => console.log('Items updated..'))
  75.     .catch(err => console.error(err.stack))
  76.  
  77.     done();
  78.     res.redirect('/api');
  79.   });
  80.   // pool shutdown
  81.   pool.end();
  82. });
  83.  
  84. // Server listen
  85. app.listen(5000, () => {
  86.   console.log("app running on port 5000");
  87. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top