Back-end/Node.js

[Node.js +MYSQL] 시퀄라이즈 (1) (Sequelize)

poppy 2021. 7. 18. 11:37
반응형
시퀄라이즈란? (Sequelize)
시퀄라이즈는 ORM 입니다. 즉, 자바스크립트 객체와 데이터베이스의 릴레이션을 매핑해주는 도구입니다. 시퀄라이즈는 여러 가지 데이터베이스와 연결할 수 있습니다. 시퀄라이즈가 자바스크립트 구문을 알아서 SQL로 바꿔주기 때문에 자바스크립트만으로 데이터베이스를 조작할 수 있습니다.

 

MYSQL 설치방법은 따로 다루지 않겠습니다! 설치가 다 완료되었다는 가정 하에 시작합니다

 

1. MYSQL에 테이블 생성하기

먼저 테이블을 생성하기 전에 테이블을 생성할 데이터베이스를 생성합니다. 다음 명령어를 MYSQL 프롬프트에 입력합니다.

create database nodejs default character set utf8;
use nodejs;

 

데이터베이스 생성 후 테이블을 생성합니다. 

mysql> create table nodejs.users (
    -> id int not null auto_increment,
    -> name varchar(20) not null,
    -> age int unsigned not null,
    -> married tinyint not null,
    -> comment text null,
    -> created_at datetime not null default now(),
    -> primary key(id),
    -> unique index name_UNIQUE (name ASC))
    -> comment = '사용자 정보'
    -> default character set = utf8
    -> engine = InnoDB;
mysql> create table nodejs.comments (
    -> id int not null auto_increment,
    -> commenter int not null,
    -> comment varchar(100) not null,
    -> created_at datetime not null default now(),
    -> primary key(id),
    -> index commenter_idx (commenter ASC),
    -> constraint commenter
    -> foreign key (commenter)
    -> references nodejs.users(id)
    -> on delete cascade
    -> on update cascade)
    -> comment = '댓글'
    -> default charset=utf8mb4
    -> engine=InnoDB;

 

2. 시퀄라이즈를 사용하기 위한 프로젝트 만들기

다음 명령어를 통해 package.json 을 생성 및 설정합니다.

npm init

 

시퀄라이즈에 필요한 것들을 설치합니다. sequelize-cli 는 시퀄라이즈 명령어를 실행하기 위한 패키지이고, mysql2 는 MYSQL 과 시퀄라이즈를 이어주는 드라이버입니다.

 npm install express morgan nunjucks sequelize sequelize-cli mysql2
 npm install -D nodemon

 

프로젝트를 생성합니다. 생성이 완료되면 config, models 등의 폴더가 생깁니다.

npx sequlize init

 

3. 시퀄라이즈와 MYSQL 연결하기

models 폴더의 index.js 파일을 다음과 같이 수정합니다. config/config.json 은 데이터베이스 설정 파일인데 이것을 불러온 후 new Sequelize 를 통해 MYSQL 연결 객체를 생성합니다.

// models/index.js
const Sequelize = require('sequelize');

const env = process.env.NODE_ENV || 'development';
const config = require('../config/config')[env];
const db = {};

const sequelize = new Sequelize(config.database, config.username, config.password, config);

db.sequelize = sequelize; // 나중에 연결 객체 재사용을 위해 넣어둠

module.exports = db;

 

config 폴더의 config.json 파일을 다음과 같이 수정합니다. 자신의 데이터베이스와 연결할 수 있도록 값을 수정하면 됩니다.

// config/config.json
{
  "development": {
    "username": "root",
    "password": "MYSQL의 root 비밀번호",
    "database": "nodejs",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
...
}

 

시퀄라이즈를 통해 익스프레스 앱과 MYSQL을 연결합니다. app.js 를 다음과 같이 작성합니다. sequelize.sync 를 통해 서버 실행시 MYSQL과 연동되도록 하였습니다. 

// app.js
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const nunjucks = require('nunjucks');

const { sequelize } = require('./models/index'); // 시퀄라이즈
const indexRouter = require('./routes');
const usersRouter = require('./routes/users');
const commentsRouter = require('./routes/comments');

const app = express();
app.set('port', process.env.PORT || 3001);
app.set('view engine', 'html');
nunjucks.configure('views', {
  express: app,
  watch: true,
});
// 서버 실행시 MYSQL과 연결
sequelize.sync({ force: false }) // 서버 실행시마다 테이블을 재생성할건지에 대한 여부
  .then(() => {
    console.log('데이터베이스 연결 성공');
  })
  .catch((err) => {
    console.error(err);
  });

app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/comments', commentsRouter);

app.use((req, res, next) => {
  const error =  new Error(`${req.method} ${req.url} 라우터가 없습니다.`);
  error.status = 404;
  next(error);
});

app.use((err, req, res, next) => {
  res.locals.message = err.message;
  res.locals.error = process.env.NODE_ENV !== 'production' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

app.listen(app.get('port'), () => {
  console.log(app.get('port'), '번 포트에서 대기 중');
});

 

모든 작업이 완료되었다면 서버를 실행합니다. 콘솔에 다음과 같은 로그가 뜨면 성공입니다!

npm start

 

반응형