Sequelize 사용해보기 + postgresql + dotenv

KimJH_94·2023년 1월 25일
0

NodeJS

목록 보기
4/4
post-thumbnail

시퀄라이지는 노드에서 DB작업을 쉽게 해주는 ORM이다. (자바스크립트 객체와 DB를 매핑해주는 도구로, JSP에서 마이바티스를 생각하면 편하다) 시퀄라이즈를 사용하면 자바스크립트 구문으로 쿼리문을 날려줄 수 있다.

1단계 : express-generator로 프로젝트 설치

  1. sudo npm install -g express-generator : express generator 설치
  2. express myapp : myapp 이라는 이름의 프로젝트 생성
  3. cd myapp -> npm install : 프로젝트로 들어가서 디펜던시 설치
    • npm start : 프로젝트 시작하는 법 (package.json에 start 아래 항목을 수정하여 변경 가능)

2단계 : DB설치 + 연결 (postgresql)

  1. brew install postgresql
    • brew reinstall postgresql@14 : 이미 설치가 되어있으면 재설치해줌
  2. postgres -V 로 버전확인
  3. psql postgres : postgres 접속
    • \du : Role Name 리스트 확인
  4. 디비버 접속해서 드라이버 연결
    • 드라이버 업데이트 : 데이터베이스 → 드라이버관리자 → postgresql → edit → Libraries → Download/Update → Download
    • db이름 3번(\du)에서 확인한 드라이버 이름으로 설정
    • test connection

추가적으로 user 생성하여 다른 테이블 만들고 싶을 때

참고) Roles (Owner) > Database (스키마)
1. psql postgres : 다시 postgres 접속
2. create database study; : study 라는 이름의 데이터베이스 생성
3. create user testuser with encrypted password '1234'; : testuser라는 이름의 유저 생성, 비밀번호는 1234
4. ALTER USER testuser CREATEDB; : testuser에게 createdb권한 부여
5. grant all privileges on database study to testuser; : study db에 대한 전권 testuser에게 부여
- \list 로 데이터베이스 리스트 보기
- \dt 로 테이블 리스트 보기
- \connect study : 해당 데이터베이스로 연결
6. psql postgres -U testuser : 해당 유저로 연결 (#은 슈퍼유저 ⇒ 은 일반유저)

3단계 : sequelize 실행 + 설정

  1. npm install sequelize : 시퀄라이즈 설치
  2. npm install sequelize-cli : 시퀄라이즈 설정 파일 설치
    • config, models, migration, seeders 폴더 생겨있어야함
  3. config > config.json에 DB 정보 담기
{
  "development": {	// 개인 개발에선 development 사용
    "username": "root",		// rolename
    "password": "root",				// 설정한 비밀번호
    "database": "test",	// database 스키마 이름
    "host": "127.0.0.1",			// 로컬호스트는 127.0.0.1로 쓰기
    "dialect": "postgres"			// db종류
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}
  1. config > index.js 에 아래 내용 정리
const Sequelize = require('sequelize');
const env = process.env.NODE_ENV || 'development';     // 개발용 환경 설정
const config = require('./config.json')[env];      // Sequelize 설정 파일
const db = {};	// 모듈화 할 때 필요한 빈 객체(이 객체가 바깥으로 모듈이 된다)

// Sequelize 인스턴스화(config 파일에 있는 정보 여기에 담아줌)
const sequelize = new Sequelize(config.database, config.username, config.password, config);  

db.Sequelize = Sequelize;  // 비어있는 db객체에 Sequelize 패키지 넣기
db.sequelize = sequelize;  // 비어있는 db객체에 Sequelize 인스턴스 넣기

module.exports = db;  // 모듈화
  1. 이제 가장 바깥에 위치한 app.js 스키마를 자동 생성시켜주는 문장을 추가해준다. (
// DB 테이블 생성 모듈
const {sequelize} = require('./config');
// DB 테이블 생성
// 개발 중에는 기존 테이블을 삭제하고 데이터베이스를 다시 동기화해야 할 수 있다. force: true다음 코드로 사용
// db.sequelize.sync({ force: true }).then(() => {
//   console.log("Drop and re-sync db.");
// });
sequelize.sync();
  1. 테이블을 만들어준다. models 디렉토리 내부에 만들어준다.
/**
 * Account 테이블 만들기  
 * @param {Sequelize} 
 * @param {DataTypes}  
 * 회원번호, 회원아이디, 비밀번호, 전화번호, 상태, 가입일
 */

module.exports = (Sequelize, DataTypes) => {
    return Sequelize.define('account', {	// 테이블 이름 (자동으로 복수형으로 바뀌게 됨)
      userid: {	// PK값은 자동으로 생성해주기 때문에 신경안써도됨
        type: DataTypes.STRING(20), // type : 자료형
        allowNull: false,			// allowNull : Null 여부
      },
      password: {
        type: DataTypes.STRING(20),
        allowNull: false,
      },
      phoneno: {
        type: DataTypes.STRING(50),
        allowNull: true,
      },
      status: { // 회원 상태 여부 (참이면 회원가입 중 거짓이면 회원 탈퇴중)
        type: DataTypes.BOOLEAN,
        allowNull: false
      },
      date: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('now()') // 회원이 생길 때 자동으로 날짜가 등록이 됨
      },
    }, {
      timestamps: false,  // 생성일을 Sequelize가 자동으로 생성하지 말라는 옵션 
      underscored: true,   // Snake Case를 권장한다는 옵션
    })
  }
  1. 이제 생성한 라우트에 create메소드를 이용하여 임의의 데이터를 넣어준다.
const express = require('express');
const router = express.Router();
const { Account } = require('../config');


// 회원가입 post
router.post('/signup', function(req, res, next){
  Account.create({	// ID는 자동으로 생성됨 (PK)
    userid : "test1",
    password : "testpw1",
    phoneno : "01000000001",
    status : "TRUE"
  })
  .then((result) => {
    res.status(200).json(result);
  })
  .catch((err) => {
    console.error(err);
    next(err);
  })
});

module.exports = router;
  1. 그 뒤 config > index.js에 해당 라우터를 모듈화 해준다.
db.Account = require('../models/account)(sequelize, Sequelize)
models.exports = db;
  1. 마지막으로 app.js에 해당 라우터를 추가해주고, 실행해주면 된다.

dotenv를 이용하여 DB 정보 옮기기

공통적으로 사용하는 설정값을 dotenv에 담아 사용하면 한결 편리하다.

  1. npm install dotenv -g : 설치
  2. root 경로에 .env파일 생성
DATABASE = "DB이름"
DB_HOST = "127.0.0.1"
DB_USER = "계정이름"
DB_PASS = "비밀번호"
DB_DIALECT = "DB종류" // postgres
  1. config > index.js 수정해주기 (.env 파일 형식에 맞게)
const Sequelize = require('sequelize');
require("dotenv").config();  // dotenv 모듈, config메소드사용
const db = {};                                             // 모듈화 할 때 필요한 빈 객체

// process.env 을 통해 .env에 작성한 데이터를 뽑아 사용할 수 있다
const sequelize = new Sequelize(process.env.DATABASE, process.env.DB_USER, process.env.DB_PASS, {
    host: process.env.DB_HOST,
    dialect: process.env.DB_DIALECT
});  

db.Sequelize = Sequelize;  // 빈 db객체에 Sequelize 패키지 넣기
db.sequelize = sequelize;  // 빈 db객체에 Sequelize 인스턴스 넣기

db.Account = require('../models/account')(sequelize, Sequelize);
module.exports = db;  // 모듈화
profile
안녕하세요.

0개의 댓글