Express, Sequelize with PostgreSQL database를 사용하여 Node.js Restful CRUD API 구현하기 step1

Think_Positively·2021년 3월 2일
0

따라하며 배우기

목록 보기
1/3

CRUD : Create(생성), Read(읽기), Update(갱신), Delete(삭제) 를 묶어서 일컫는 말이다.

  • 사용할 Rest APIs
  • 최종 파일 구성


1. 폴더 생성 및 nodejs 시작

  • mkdir 폴더명 / cd 폴더명
  • npm init (nodejs 시작 / package.json파일 생성)
  • description 빼고는 전부 enter누름
  • yes

생성한 폴더 아래 추가적으로 app폴더 그 안에 config, controllers, models, routes 폴더까지만 생성


2. 필요 모듈 설치

  • express, sequelize, pg, pg-hstore, body-parser

    npm install express sequelize pg pg-hstore body-parser cors --save

  • 설치 완료

  • 현재 package.json 모습


3. Express 서버 설정

server.js 생성

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();

var corOptions = {
  origin: "http://localhost:8081",
};

app.use(cors(corOptions));

// parse requests of content-type - application/json
app.use(bodyParser.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to my application." });
});

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on Port ${PORT}!`);
});
  • express, body-parser, cors import(require)
  • express app 생성, app.use() 를 이용하여 body-parser, cors 추가
  • node server.js 실행 후 http://localhost:8080/ 접속


4. PostgreSQL database & Sequelize 설정

  • config 폴더에 db.config.js 파일 생성
module.exports = {
	HOST: "localhost",
  	USER: "postgres",
  	// password에는 설치할때 설정한 비밀번호 입력!
  	PASSWORD: "1234"
  	DB: "my_DB",
  	dialect: "postgres"
  	pool: {
		max: 5,
  		min: 0,
  		acquire: 30000,
  		idle: 10000
	}
};
  • host, user, password, db, dialect는 PostgreSQL과 연결을 위한 정보
  • pool은 option
    • max : Maximum number of connection in pool
    • min : Minimum number of connection in pool
    • acquire : The maximum time, in milliseconds, that pool will try to get connection before throwing error
    • idle : The maximum time, in milliseconds, that a connection can be idle before being released.

5. Initialize Sequelize

app/models 폴더에 index.js 생성

const dbConfig = require('../config/db.config.js');

const Sequelize = require('sequelize');
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
	host: dbConfig.HOST,
  	dialect: dbConfig.dialect,
  	operatorsAliases: false,
  
  	pool: {
    	max: dbConfig.pool.max,	
   		min: dbConfig.pool.min,
      	acquire: dbConfig.pool.acquire,
      	idle: dbConfig.pool.idle
    }
});

const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.tutorials = require("./tutorial.model.js")(sequelize, Sequelize);

module.exports = db;
  • server.js 에서 sync() method 작성

6. Sequelize 모델 작성

models 폴더에 tutorial.model.js 생성

module.exports = (sequelize, Sequelize) => {
	const Tutorial = sequelize.define("tutorial", {
		title: {
  			type: Sequelize.STRING
		},
  		description: {
  			type: Sequelize.STRING
		},
      		published: {
  			type: Sequelize.BOOLEAN
		}
	});

	return Tutorial
};
  • PostgreSQL에 만들어질 "tutorial" 테이블을 나타낸다.
  • id, title, description, published, createdAt, updatedAt 컬럼들이 자동생성된다.

CRUD method 작성법은 다음 시간에.


용어 정리)

Express : Nodejs 서버 프레임워크
Sequelize : 쉽게 서버와 연결해주는 nodejs(javascript) 라이브러리
pg : PostgreSQL을 사용하기 위한 모듈
pg-hstore : 데이터를 PostgreSQL hstore type 으로 변환해주는 모듈
body-parser : 요청 구문분석 and req.body 생성에 필요
cors : Express 미들웨어에서 CORS 사용을 위해 설치

CORS는 Cross Origin Resource Sharing의 약자로 도메인 및 포트가 다른 서버로 클라이언트가 요청했을 때 브라우저가 보안상의 이유로 API를 차단하는 문제입니다. 예로 들면 로컬에서 클라이언트는 3000 포트로 서버는 10000 포트로 서버를 띄웠을때 또는 로컬 서버에서 다른 서버로 호출할 때 발생하게 됩니다.
출처 : https://firework-ham.tistory.com/70


References
https://bezkoder.com/node-express-sequelize-postgresql/

profile
데이터 엔지니어를 꿈꾸며

0개의 댓글