Runtime/Node.js

15. Sequelize 사용

김엉배 2023. 3. 12. 22:43
728x90
반응형

 

1.  model 만들기

 - MySQL에 생성되어 있는 customers 테이블 매핑을 위한 모델 생성

  • 터미널에서 sequelize-cli를 이용하여 명령어를 통해 customers 테이블을 매핑하기 위한 모델을 정의하는 js파일을 생성할 수 있다.
sequelize-cli model:generate --name 테이블명 --attributes attr1:type,attr2:type

 

  • customers 테이블에 id, name, email, phone, address 칼럼이 있고, primary key인 id를 제외한 4개의 칼럼에 대해 입력
sequelize-cli model:generate --name customers --attributes id:integer,name:string,email:string,
phone:string,address:string

 

  • models 폴더에 customers.js 파일 생성이 된다.

customers.js

 

  • customers.init() 함수에 timestamps: false 옵션 추가 및 정의한 칼럼 정보를 구체적으로 정의

속성 타입 설명
type DataTypes STRING, INEGER, BIGINT 등
allowNull Boolean Null 허용 여부(default:true)
defaultValue any 기본값(default: null)
unique Boolean 유일한 값 여부(default: false)
primaryKey Boolean pk값 여부(default: false)
autoIncrement Boolean 자동 1증가 (default: false)

 

2.  데이터 조회

  •  app_sequelize.js 파일 생성

findAll() 함수를 이용해 customers 테이블에 있는 전체 데이터를 조회할 수 있다.

 - findAll(조건) : 조건을 만족하는 전체 데이터 조회, 조회 조건이 없는 경우 테이블 전체를 조회

 - findByPK(pk): pk값을 파라미터로 전달해서 데이터 조회

 - findOne(조건) 조건을 만족하는 데이터 중 첫 번째 데이터 조회

 

3.  데이터 추가

  • 테이블에 데이터를 추가할 때는 create() 함수 사용
const result = await customers.create({name: 'James', email: 'james@emali.com',
phone: '010-2222-2222', address: ''});
console.log(result.id);
  • 클라이언트로부터 전송된 고객 정보를 테이블에 추가하기 위한 라우트 추가

 

 

4.  데이터 수정

  • 테이블 데이터를 수정할 때 update() 함수를 사용
await User.update({ phone: "010-7777-7777" }, { where: { id: 5 }});
  • 고객 정보를 수정하기 위한 라우트를 추가

 

5.  데이터 삭제

  • 테이블의 데이트를 삭제할 때는 destroy() 함수를 사용
awit customers.destroy({
	where: { id: id}
});
  • 고객 정보를 삭제하기 위한 라우트를 추가


  • 전체 코드
const express = require("express");
const customers = require("./models/customers");
const sequelize = require('./models').sequelize;
const app = express();

sequelize.sync();

app.use(express.json({
  limit: '50mb'
}));

app.listen(3000, () => {
  console.log('Server started. port 3000.');
})

// 고객 정보 라우터
app.get('/api/customers', async(req, res) => {
  const customersData = await customers.findAll();
  console.log(customersData);
  res.send(customersData);
});

// 고객 정보 추가 라우터
app.post('/api/customers/insert', async(req, res) => {
  const {name, email, phone, address} = req.body.params;
  const result = await customers.create({name:name, email:email, phone: phone, address: address});
  res.send(result);
});

// 고객 정보 수정 라우트
// 클라이언트가 서버 호출 시 body에 json 형식으로 params 키로 배열 전송
// ex) {params: [{phone: "010-6666-7777"}, 5]}
app.put('/api/customer/update', async(req, res) => {
  const result = await customers.update(req.body.params[0], {
    where: {id: req.body.params[1]}
  });
  res.send(result);
});

// 고객 정보 삭제 라우터
app.delete('api/customer/delete/:id', async(req, res) => {
  const {id} = req.params;
  const result = await customers.destroy({
    where: {id: id}
  });
  res.send(result);
});
728x90
반응형