Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const express = require('express');
- const router = express.Router(); //handles the routing of incoming requests
- const pg = require('pg'); //Non-blocking PostgreSQL client for node.js.
- const connectionString = 'postgres://localhost:5432/todo';
- const app = express();
- //blocks header from containing server info
- app.disable('x-powered-by');
- //set "main" as default layout, with handlebars as the engine
- const handlebars = require('express-handlebars').create({ defaultLayout: 'main' });
- app.engine('handlebars', handlebars.engine);
- //set html as defined in "views" directory to be transported into "main.handlebars" layout
- app.set('view engine', 'handlebars');
- //When the user submits the URL, it hits this app.use and deciphers it here. Make sure routes are below this.
- app.use(require('body-parser').urlencoded({
- extended: true
- }));
- app.set('port', process.env.PORT || 3000);
- //use this to import images/etc
- app.use(express.static(__dirname + '/public'));
- //define roots, request object, response object
- app.get('/', function (req, res) {
- //render html
- res.render('home');
- });
- //middleware
- app.use(function (req, res, next) {
- console.log("Looking for URL : " + req.url);
- next();
- });
- /*app.get('/junk', function (req, res, next) {
- console.log('Tried to access /junk');
- throw new Error('/junk doesn\'t exist');
- });*/
- app.use(function (err, req, res, next) {
- console.log('Error : ' + err.message);
- next();
- });
- /*
- //about.handlebars
- app.get('/about', function (req, res) {
- //render html
- res.render('about');
- });*/
- // /:id will match anything after the / in the url, and set it as the req.params.id value
- app.get('/:id', function (req, res) {
- console.log("hi you're about to match url id to database id");
- //get a prostgres client from the connection pool
- pg.connect(connectionString, (err, client, done) => {
- //handle connection errors
- if (err) {
- done();
- console.log(err);
- return res.status(500).json({ success: false, data: err });
- }
- //match id in database to id from query in url
- const query = client.query("SELECT * FROM items WHERE id =" + req.params.id);
- console.log("successfully matched in database to id in url");
- console.log(req.query);
- res.redirect(res.query);
- });
- });
- /*
- app.use(function (req, res) {
- res.type('text/html');
- res.status(404);
- res.render('404');
- });
- app.use(function (err, req, res, next) {
- console.error(err.stack);
- res.status(500);
- res.render('500');
- });*/
- app.listen(app.get('port'), function () {
- console.log("Express started on http://localhost:" + app.get('port'));
- });
- //The routes all needs to be below the middleware.
- //enable the router
- app.use('/', router);
- //Create
- router.post('/createShorter', (req, res, next) => {
- const results = [];
- console.log("Congrats you hit the create function!!");
- console.log(req.body);
- //grab data from http-request, complete is from boolean in database
- const data = { text: req.body.url, complete: false };
- //give error if request if "bad request"
- if (!req.query.text) res.send(400, "The Request data is: " + req.query);
- //get a prostgres client from the connection pool
- pg.connect(connectionString, (err, client, done) => {
- //handle connection errors
- if (err) {
- done();
- console.log(err);
- return res.status(500).json({ success: false, data: err });
- }
- //SQL Query -> Insert Data
- client.query('INSERT INTO items(original_url, complete) values($1,$2)',
- [data.text, data.complete]);
- //SQL Query -> Select Data
- const query = client.query("SELECT * FROM items ORDER BY id ASC");
- //Stream results back one row at a time
- query.on('row', (row) => {
- results.push(row);
- });
- //After all data is returned, close connection and return the results
- query.on('end', () => {
- done();
- //return res.json(results);
- //return res.json(data);
- });
- });
- });
- //READ **check here with http://localhost:3000/createShorter
- //selects and displays results
- router.get('/api/v1/requests', function (req, res) {
- let results = [];
- //get prostgres client from connection pool
- pg.connect(connectionString, function (err, client, done) {
- if (err) {
- done();
- console.log(err);
- return res.status(500).json({ success: false, data: err });
- }
- //SQL Query -> Select Data
- const query = client.query("SELECT * FROM items ORDER BY id ASC;");
- //Stream results back one row at a time
- query.on('row', function (row) {
- results.push(row);
- });
- //After all data is returned, close connection and return results
- query.on('end', function () {
- done();
- return res.json(results);
- });
- });
- });
- //UPDATE
- //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
- router.put('/api/v1/todos/:todo_id', function (req, res) {
- console.log("congrats you hit the update function.");
- const results = [];
- //grab data from the URL parameters
- const id = req.params.todo_id;
- //Grab data from http-request (gets, text and marks process complete)
- const data = { text: req.query.text, complete: req.query.complete };
- console.log(data);
- //Get a Postgres client from the connection pool
- pg.connect(connectionString, function (err, client, done) {
- if (err) {
- done();
- console.log(err);
- return res.status(500).send(json({ success: false, data: err }));
- }
- // SQL QUERY -> Update Data
- client.query('UPDATE items SET original_url=($1), complete=($2) WHERE id=($3)',
- [data.text, data.complete, id]);
- //SQL Query -> Select Data
- const query = client.query("SELECT * FROM items ORDER BY id ASC");
- //Stream results back one row at a time
- query.on('row', function (row) {
- results.push(row);
- });
- //After all data is returned, close connection and return results
- query.on('end', function () {
- done();
- return res.json(results);
- });
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement