안녕하세요 깍돌이입니당 ~

저번 포스팅까지는 Mysql 8.0 을 서버에 설치하고  간단하게 SQL 문 등 몇가지 테스트만 해보았는데요

이제는 해당서버에 있는 DB와 연동하기 위한 Manager 서버를 구성하려고 합니다.

 

Node.js 관련 포스팅은 다른글에도 있고 하니 기본적인건 제외 하고 시작 하도록 하겠습니다.

 

Package.json

해당 파일 이미지를 통해 어떠한 부분을 생성하였고 안하였는지 체크 하면 될 것 같습니다.

devDependencies -> npm i -D [모듈명] 으로 설치 한 모듈입니다.

dependencies ->npm i 로 [모듈명] 으로 설치 한 모듈입니다.

** mysql2 의 @types 는  npm i -D types/mysql2 으로 설치합니다.

  "dependencies": {
    "axios": "^0.20.0",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "helmet": "^4.1.0",
    "moment": "^2.27.0",
    "mysql2": "^2.1.0"
  },
  "devDependencies": {
    "@types/axios": "^0.14.0",
    "@types/cookie-parser": "^1.4.2",
    "@types/cors": "^2.8.7",
    "@types/express": "^4.17.7",
    "@types/moment": "^2.13.0",
    "@types/multer": "^1.4.4",
    "@types/mysql2": "github:types/mysql2",
    "@types/node": "^14.6.2",
    "@types/node-cron": "^2.0.3",
    "@types/serve-favicon": "^2.5.0",
    "pm2": "^4.4.1",
    "typescript": "^4.0.2"
  }

위와같이 설치 되었습니다. ( 작업하다 더 늘어나면 해당 글에 최신화를 할 예정입니다. )

현재 mysql8에는 

위와같이 테스트 데이터를 넣어 놓은 상태입니다.

 

Node.js에서 해당 파일을 mysql2 모듈을 이용해서 CRUD 하는 작업을 간단하게 작성 하도록 하겠습니다.

 

Express & TypeScript

Express.js를 TypeScript로 일단 기본 미들웨어 세팅을 구성하려고 합니다.

 

github.com/lgance/network.git

 

lgance/network

Contribute to lgance/network development by creating an account on GitHub.

github.com

위의 network 로 되어있는 프로젝트가 typescript & Express.js의 Boilerplate code 입니다. 현재는 더이상 사용하거나 추가하지 않기 때문에 위의 프로젝트를 기준으로 작성 하겠습니다.

 

Mysql 연결

기본적인 틀은 위의 github을 통해서 작성을 한 상태로 Mysql 을 연결하는 Router 만 작성하도록 하겠습니다.

 

import * as express from 'express';
import Controller from '../interface/controller.interface'


class ActionStatusController implements Controller {
  public path='/action';
  public pathId='/action/:id';
  public router = express.Router();

  constructor(){
    this.initializeRoutes();
  }
  private initializeRoutes(){
    /** 모든 액션 가져오기  */
    this.router.get(this.path,this.readAllActionStatus);
    /** 특정 액션 가져오기 */
    this.router.get(this.pathId,this.readActionStatus);
    /** 특정 액션 지우기*/
    this.router.delete(this.pathId,this.deleteActionStatus);
    /** 액션 생성 */
    this.router.post(this.pathId,this.createActionStatus);
    /** 액션 변경 */
    this.router.put(this.pathId,this.updateActionStatus);
  }

  private readAllActionStatus = async (req:express.Request,res:express.Response)=>{
    const _str = this._LOG(req).concat(' Read All Action Status');
    res.send(_str);
  }
  private createActionStatus = async(req:express.Request,res:express.Response)=>{
    const _str = this._LOG(req).concat(' Create Action Status');
    res.send(_str);
  }
  private readActionStatus = async (req:express.Request,res:express.Response)=>{
    const _str = this._LOG(req).concat(' Read Action Status');
    res.send(_str);
  }
  private updateActionStatus = async(req:express.Request,res:express.Response)=>{
    const _str = this._LOG(req).concat(' Update Action Status');
    res.send(_str);
  }
  private deleteActionStatus = async(req:express.Request,res:express.Response)=>{
    const _str = this._LOG(req).concat(' Delete Action Status');
    res.send(_str);
  } 

  private _LOG = (req:express.Request):string => {
    const id:string = req.params.id;
    console.log(`Check ID : [${id}]`);
    if(id===undefined){
      return '';
    }
    else{
      return id;
    }
  }

}
export default ActionStatusController;

기본적으로 action Controller를 하나 생성합니다.

 

각각의 기본적인 CRUD를 작성하겠습니다. ( 테스트용 ) 

초반이니까 얼렁 얼렁 작성해서 ㅎㅎ;;

 

일단  http://localhost/action 로 접속 해서 확인해봅시다.

 

정상적으로 나왔으니까 이제 mysql2을 이용하여서 간단한 쿼리로 SELECT 문을 이용하여 가져와 봅니다.

 

mysql 모듈 Import

import * as mysql from 'mysql2';

DB Config 파일 설정 

 private db_config = {
    "host":process.env.DB_HOST,
    "user":process.env.DB_USERNAME,
    "password":process.env.DB_PASSWORD,
    "database":process.env.DB_NAME
  }

ReadAllActionStatus Controller 수정 

 private readAllActionStatus = async (req:express.Request,res:express.Response)=>{
    const _str = this._LOG(req).concat(' Read All Action Status');
    const table = 'status_table';
    const query = `SELECT * FROM ${table}`;

    const connection = mysql.createConnection(this.db_config);
    connection.connect();

    connection.query(query,function(error,results,fields){
      if (error) throw error;
      console.log(results);
  
      res.send(results);
      console.log('connected as id ' + connection.threadId);
    });
    connection.end();
   
  }

 

 

결과는 ? 

 

네 정상적으로 연결되어 값을 가져옴을 확인하였습니다.  하지만 여러가지 문제가 있습니다.

 

1. query Callback 

connection.query 의 Callback 으로 결과를 받은 후에 res.send 를 해주기 때문에 Client한테 지연을 줄수 있습니다. (좋은방법 X)

 

2. SQL Injection 

sql injection 에 당하기 딱 좋은 방법이죠 위의 코드에선 안당하겠지만 (너무단순한 SQL 문이라)

이부분을 유의하여서 앞으로 작성하도록 하겠습니다.

 

감사합니다.

 

Thanks for always

 

 

 

 

 

 

 

 

+ Recent posts