Advertisement
Guest User

Untitled

a guest
Oct 14th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const express = require('express');
  4. const router = express.Router(); //handles the routing of incoming requests
  5. const pg = require('pg'); //Non-blocking PostgreSQL client for node.js.
  6. const connectionString = 'postgres://localhost:5432/todo';
  7. const app = express();
  8.  
  9. //blocks header from containing server info
  10. app.disable('x-powered-by');
  11. //set "main" as default layout, with handlebars as the engine
  12. const handlebars = require('express-handlebars').create({ defaultLayout: 'main' });
  13. app.engine('handlebars', handlebars.engine);
  14. //set html as defined in "views" directory to be transported into "main.handlebars" layout
  15. app.set('view engine', 'handlebars');
  16.  
  17. //When the user submits the URL, it hits this app.use and deciphers it here. Make sure routes are below this.
  18. app.use(require('body-parser').urlencoded({
  19.   extended: true
  20. }));
  21.  
  22. app.set('port', process.env.PORT || 3000);
  23. //use this to import images/etc
  24. app.use(express.static(__dirname + '/public'));
  25.  
  26. //define roots, request object, response object
  27. app.get('/', function (req, res) {
  28.   //render html
  29.   res.render('home');
  30. });
  31.  
  32. //middleware
  33. app.use(function (req, res, next) {
  34.   console.log("Looking for URL : " + req.url);
  35.   next();
  36. });
  37.  
  38. /*app.get('/junk', function (req, res, next) {
  39.   console.log('Tried to access /junk');
  40.   throw new Error('/junk doesn\'t exist');
  41. });*/
  42.  
  43.  
  44. app.use(function (err, req, res, next) {
  45.   console.log('Error : ' + err.message);
  46.   next();
  47. });
  48. /*
  49. //about.handlebars
  50. app.get('/about', function (req, res) {
  51.   //render html
  52.   res.render('about');
  53. });*/
  54.  
  55.  
  56. // /:id will match anything after the / in the url, and set it as the req.params.id value
  57. app.get('/:id', function (req, res) {
  58.   console.log("hi you're about to match url id to database id");
  59.   //get a prostgres client from the connection pool
  60.   pg.connect(connectionString, (err, client, done) => {
  61.     //handle connection errors
  62.     if (err) {
  63.       done();
  64.       console.log(err);
  65.       return res.status(500).json({ success: false, data: err });
  66.     }
  67.     //match id in database to id from query in url
  68.     const query = client.query("SELECT * FROM items WHERE id =" + req.params.id);
  69.     console.log("successfully matched in database to id in url");
  70.     console.log(req.query);
  71.     res.redirect(res.query);
  72.   });
  73. });
  74. /*
  75. app.use(function (req, res) {
  76.   res.type('text/html');
  77.   res.status(404);
  78.   res.render('404');
  79. });
  80.  
  81. app.use(function (err, req, res, next) {
  82.   console.error(err.stack);
  83.   res.status(500);
  84.   res.render('500');
  85. });*/
  86.  
  87. app.listen(app.get('port'), function () {
  88.   console.log("Express started on http://localhost:" + app.get('port'));
  89. });
  90.  
  91. //The routes all needs to be below the middleware.
  92.  
  93. //enable the router
  94. app.use('/', router);
  95.  
  96. //Create
  97. router.post('/createShorter', (req, res, next) => {
  98.   const results = [];
  99.   console.log("Congrats you hit the create function!!");
  100.   console.log(req.body);
  101.   //grab data from http-request, complete is from boolean in database
  102.   const data = { text: req.body.url, complete: false };
  103.  
  104.   //give error if request if "bad request"
  105.   if (!req.query.text) res.send(400, "The Request data is: " + req.query);
  106.   //get a prostgres client from the connection pool
  107.   pg.connect(connectionString, (err, client, done) => {
  108.     //handle connection errors
  109.     if (err) {
  110.       done();
  111.       console.log(err);
  112.       return res.status(500).json({ success: false, data: err });
  113.     }
  114.  
  115.     //SQL Query -> Insert Data
  116.     client.query('INSERT INTO items(original_url, complete) values($1,$2)',
  117.       [data.text, data.complete]);
  118.  
  119.     //SQL Query -> Select Data
  120.     const query = client.query("SELECT * FROM items ORDER BY id ASC");
  121.  
  122.     //Stream results back one row at a time
  123.     query.on('row', (row) => {
  124.       results.push(row);
  125.     });
  126.  
  127.     //After all data is returned, close connection and return the results
  128.     query.on('end', () => {
  129.       done();
  130.       //return res.json(results);
  131.       //return res.json(data);
  132.     });
  133.   });
  134. });
  135.  
  136.  
  137. //READ  **check here with http://localhost:3000/createShorter
  138. //selects and displays results
  139. router.get('/api/v1/requests', function (req, res) {
  140.   let results = [];
  141.  
  142.   //get prostgres client from connection pool
  143.   pg.connect(connectionString, function (err, client, done) {
  144.     if (err) {
  145.       done();
  146.       console.log(err);
  147.       return res.status(500).json({ success: false, data: err });
  148.     }
  149.  
  150.     //SQL Query -> Select Data
  151.     const query = client.query("SELECT * FROM items ORDER BY id ASC;");
  152.  
  153.     //Stream results back one row at a time
  154.     query.on('row', function (row) {
  155.       results.push(row);
  156.     });
  157.  
  158.     //After all data is returned, close connection and return results
  159.     query.on('end', function () {
  160.       done();
  161.       return res.json(results);
  162.     });
  163.   });
  164. });
  165.  
  166. //UPDATE
  167. //listens for a PUT request, for example http://127.0.0.1:3000/api/v1/todos/1?text=HiThere&complete=true will update the text and complete of database ID of 1
  168. router.put('/api/v1/todos/:todo_id', function (req, res) {
  169.   console.log("congrats you hit the update function.");
  170.   const results = [];
  171.  
  172.   //grab data from the URL parameters
  173.   const id = req.params.todo_id;
  174.  
  175.   //Grab data from http-request (gets, text and marks process complete)
  176.   const data = { text: req.query.text, complete: req.query.complete };
  177.   console.log(data);
  178.   //Get a Postgres client from the connection pool
  179.   pg.connect(connectionString, function (err, client, done) {
  180.     if (err) {
  181.       done();
  182.       console.log(err);
  183.       return res.status(500).send(json({ success: false, data: err }));
  184.     }
  185.  
  186.     // SQL QUERY -> Update Data
  187.     client.query('UPDATE items SET original_url=($1), complete=($2) WHERE id=($3)',
  188.       [data.text, data.complete, id]);
  189.  
  190.     //SQL Query -> Select Data
  191.     const query = client.query("SELECT * FROM items ORDER BY id ASC");
  192.  
  193.     //Stream results back one row at a time
  194.     query.on('row', function (row) {
  195.       results.push(row);
  196.     });
  197.  
  198.     //After all data is returned, close connection and return results
  199.     query.on('end', function () {
  200.       done();
  201.       return res.json(results);
  202.     });
  203.   });
  204. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement