Angular, MySQL, Express Summary

  1. Work with Postman.
    1. Create Collection Mission4 .
    2. Create Get request
      localhost:5000/api/items
    3. Create Post request
      localhost:5000/api/items
      • Select POST request
      • Body Type: raw
      • Select JSON
      • Body Content:
          {
            "name": "test",
            "status": true
          }
                      

  2. Open VC Code for this project only.
  3. Create project mission4 in VS Code.
  4. Put .gitignore file into this folder.
  5. Create myNotes.txt file in this folder.

  6. Angular
    1. Install Angular
        cd mission4
        ng new client
      
    2. Clean files.
    3. Install Bootstrap
          cd client
          npm i bootstrap
        
    4. Add to the project
      • Way 1

        In style.css write

        @import "bootstrap/dist/css/bootstrap.min.css";
                      

      • Way 2

        Update angular.json file.

                    
            "styles": [
              "src/styles.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],                     
          
    5. Create Proxy
      1. Create proxy.conf.json file under client folder with:
          {
            "/api/*": {
              "target": "http://localhost:5000",
              "secure": false
            }
          }
        
      2. Update angular.json file.
          ...
          "serve": {
            "builder": "@angular-devkit/build-angular:dev-server",
            "options": {
              "browserTarget": "client:build",
              "proxyConfig": "proxy.conf.json"    <-------- Add this line only!!!
            },
        

  7. Install Server Side packages
    Create server.js file.
    npm init -y
    npm i express mysql
    npm i -D nodemon concurrently

    Update package.json file

            "scripts": {
              "start": "node server.js",
              "server": "nodemon server.js --ignore ./client",
              "client": "npm start --prefix client"
            },
          

  8. Work with MySQL Workbench
    1. Create database
      CREATE DATABASE mission4;
           CREATE USER 'johnBryce_user'@'localhost' IDENTIFIED BY 'myPassword';
           SELECT * FROM mysql.user;
      GRANT ALL PRIVILEGES ON mission4.* TO 'johnBryce_user'@'localhost';
      FLUSH PRIVILEGES;
    2. Create Tables
      •     CREATE TABLE IF NOT EXISTS mission4.companies (
              id INT AUTO_INCREMENT PRIMARY KEY,
              companyName CHAR(100) NOT NULL
              );
                      
      •     CREATE TABLE mission4.servers (
              id INT AUTO_INCREMENT PRIMARY KEY,
              serverName CHAR(100) NOT NULL,
              ip CHAR(255) NOT NULL,
              hostCompId INT NOT NULL,
              status BOOLEAN DEFAULT FALSE,
              createdAt TIMESTAMP DEFAULT NOW(),
              FOREIGN KEY (hostCompId) REFERENCES mission4.companies(id)
            );
                      
      •   CREATE TABLE IF NOT EXISTS mission4.products (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name CHAR(100) NOT NULL,
            price INT NOT NULL,
            vendorId INT NOT NULL,
            units INT NOT NULL DEFAULT 0,
            updatedAt TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,   
            FOREIGN KEY (vendorId) REFERENCES mission4.vendors(id)
          );                
                      
    3. Init Tables

      •     INSERT INTO mission4.companies 
              (companyName)
              VALUES 
                ('IBM'),
                ('Microsoft'),
                ('Google'),
                ('DigitalO');
                        
      •       INSERT INTO mission4.servers 
                (serverName, ip, hostCompId)
                VALUES 
                  ('Server A', '1.1.1.1', 1),
                  ('Server B', '2.2.2.2', 2),
                  ('Server C', '3.3.3.3', 3),
                  ('Server D', '4.4.4.4', 4);                
            
      •     INSERT INTO mission4.servers 
              (serverName, ip, hostCompId, status, createdAt)
              VALUES 
                ('Server F', '10.116.093.192',  3,  1, "2010-01-31 19:00:00"),
                ('Server G', '10.010.093.102',  4,  0, "2016-02-29 18:00:00"),
                ('Server H', '10.100.100.100',  3,  1, "2019-03-31 20:00:00"),
                ('Server T', '10.170.193.132',  1,  0, "2018-04-30 19:30:00");
                      
    4. Run queries in Workbench
      • GET
            SELECT s.id, s.serverName, s.ip, s.hostCompId, s.status, s.createdAt, c.id, c.companyName
            FROM mission4.servers AS s
            LEFT JOIN mission4.companies AS c
            ON s.hostCompId = c.id
                      
      • INSERT

        See above

      • UPDATE
            UPDATE mission4.servers 
            SET status = true
            WHERE id = 1
                      
      • DELETE
            DELETE 
            FROM mission4.tasks 
            WHERE id = 7;              
                      

  9. Server Side
    1. database/db.js file
                  const mysql = require('mysql');
      
                  const pool = mysql.createPool({
                    connectionLimit: 10,
                    host: 'localhost',
                    user: 'johnBryce_user',
                    password: 'myPassword',
                    database: 'mission4'
                  });
                  
                  pool.on('connection', () => console.log('Mysql connection'));
                  /* pool.query('SELECT * FROM servers', (err, res) => {
                    if (err) throw err;
                    console.log(res);
                  }); */
                  
                  module.exports = { pool };            
                

    2. server.js file
                  const express = require('express');
                  const { pool } = require('./database/db');
                  const app = express();
      
                  app.use(express.json());
                  
                  // GET
                  app.get('/api/items', (req, res) => {            
                    res.status(200).json({});
                  });
      
                  // POST
                  app.post('/api/items', (req, res) => {
                    res.status(200).json({});
                  });
      
                  const PORT = process.env.PORT || 5000;
                  app.listen(PORT, console.log(`Server started on port ${PORT}`));
                

    3. GET
                  // GET
                  app.get('/api/servers', (req, res) => {
                    const sql = `
                      SELECT s.id, s.serverName, s.ip, s.hostCompId, s.status, s.createdAt, c.id, c.companyName
                      FROM servers AS s
                      LEFT JOIN companies AS c
                      ON s.hostCompId = c.id
                    `;
                    pool.query(sql, (err, results) => {
                      if (err) {
                        res.status(500).json({success: false});
                        throw err;
                      }
                      res.status(200).json({success: true, data: results});
                    });  
                  });
                

    4. POST
                  // POST
                  app.post('/api/todolist', (req, res) => {
                    const { taskName, ownerId } = req.body;
                  
                    //Validation
                    if (isNaN(Number(ownerId)) || !taskName) {
                      return res.status(400).json({success: false});
                    }
                  
                    const newTask = { taskName, ownerId };
                  
                    const sql = `
                      INSERT INTO tasks 
                      SET ?
                    `;
                    pool.query(sql, [newTask], (err, results, fields) => {
                      if (err) {
                        res.status(400).json({success: false});
                        throw err;
                      }
                      res.status(200).json({success: true});
                    })
                  });            
                

    5. PUT
                  // PUT
                  app.put('/api/server/status', (req, res) => {
      
                    const { status, id } = req.body;
                  
                    // Validation
                    if (isNaN(Number(id)) || ![true, false].includes(status)) {
                      console.log('Validation has failed.');
                      return res.status(400).json({success: false});
                    }
                  
                    const sql = `
                      UPDATE servers
                      SET status = ?
                      WHERE id = ?
                    `;
                  
                    pool.query(sql, [status, id],  (err, results) => {
                      if (err) {
                        res.status(500).json({success: false});
                        throw err;
                      }
                      res.status(200).json({success: true});
                    });
                  });            
                

    6. DELETE
                    //DELETE
                    app.delete('/api/todolist/:id', (req, res) => {
      
                      const taskId = req.params.id;
                    
                      //Validation
                      if (isNaN(Number(taskId))) {
                        return res.status(400).json({success: false});
                      }
                    
                      const sql = `
                        DELETE 
                        FROM tasks 
                        WHERE id = ?;
                      `;
                    
                      pool.query(sql, [taskId], (err, results, fields) => {
                        if (err) {
                          res.status(400).json({success: false});
                          throw err;
                        }
                        res.status(200).json({success: true});
                      });
                    });              
                  

  10. Client Side See Angular Summary

xx - angular_mysql_starter_pack -