ORM?
DB의 entity,record에 접근할때, 자바스크립트의 객체나 클래스의 형태로 만질 수 있음
(애플리케이션과 db사이를 맵핑시켜주는 도구)
sequelize는 a promise-based Node.js ORM
sequelize 지원 RDBMS (mysql, mariadb, sqlite, postgres, ms sql server)
npm install --save sequelize
npm install --save-dev sequelize-cli
npx sequelize-cli init
`config`: contains config file, which tells CLI how to connect with database
`models`: contains all models for your project
`migrations`: contains all migration files
`seeders`: contains all seed files
위의 4개의 폴더를 자동으로 생성해준다(직접 dir만들지 않아도 된다.)
npx sequelize-cli --help
"development": {
"username": "root",
"password": null,
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql",
"port" : 8080
}
npx sequelize-cli model:generate --name 모델이름 --attributes 필드1:필드타입, 필드2:필드타입,필드3:필드타입
model/생성한모델명.js
그리고 migrations/[타임스탬프]-create-모델명.js
npx sequelize-cli db:migrate
desc 생성한 테이블명
sequelize db:migrate:undo
const models = require("./models");
또는Create (생성) : Post에서 사용됨
모델.create({ firstname: "chulsu" }) .then((data)=> { res.status(201).send(data); })
Read (조회)
모델.findAll() .then((data)=> { res.status(200).send(data); })
findAll()
Update (수정) : 수정할것 가져오고 업데이트를 진행
모델.findOne({ where: { firstname: "chulsu" } }) .then(data => { if (data) { data.update({ firstname: "yunhee" }) res.send(data.url); } });
DELETE (삭제) : destroy()
모델.destroy({ where: { firstname: "chulsu" }}) .then( data => console.log("deleted"));
1.줄이고 싶은 url을 넣는다
2.shorten을 누른다
3.축약된 링크가 생성된다
4.해당링크를 누르면 원본 url로 이동한다.
[post links 컨트롤러]
1.url을 포스트 요청으로 받는다.
{ url: github.com} 이러한 형태로 받음
2.요청에 있는 주소를 db에 레코드로 생성함.
-url이 저장이 되고
-url의 id가 저장이 되고
-title이 저장되고
-방문횟수가 저장이 된다(이부분은 업데이트도 진행해야함)
3.만약 이미 존재하는 url이라면, 그냥 넘어간다.
[get links/:id 컨트롤러 ]
4.links/1 get요청이 오면
5.id를 통해 레코드를 조회
6.해당 레코드의 url을
7.컨트롤러에서 리다이렉트시킴
8.그리고 visits필드 값을 1 추가함
Models can be defined in two equivalent ways in Sequelize:
Calling sequelize.define(modelName, attributes, options) API documentation on define
Extending Model and calling init(attributes, options) API documentation on init
After a model is defined, it is available within sequelize.models by its model name.
Internally, sequelize.define calls Model.init, so both approaches are essentially equivalent.```