[TIL] MVC(Model-View-Controller) & ORM

Captainjack·2021년 5월 25일
0

TIL

목록 보기
35/258

MVC(Model-View-Controller)

Model–view–controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces that divides the related program logic into three interconnected elements.

mvc는 소프트웨어가 돌아가는 디자인 패턴이라고 보면 된다.

Controller
사용자가 접근 한 URL에 따라서 사용자의 요청사항을 파악한 후에 그 요청에 맞는 데이터를 Model에 의뢰하고, 데이터를 View에 반영해서 사용자에게 알려준다.

Model
일반적으로 CI의 모델은 데이터베이스 테이블에 대응된다. 이를테면 Topic이라는 테이블은 topic_model이라는 Model을 만든다. 그런데 이 관계가 강제적이지 않기 때문에 규칙을 일관성 있게 정의하는 것이 필요하다.

View
View는 클라이언트 측 기술인 html/css/javascript들을 모아둔 컨테이너이다.

  1. Model은 데이터 베이스와 연결되어있어서, 데이터를 주고 받는다.
  2. View는 유저에게 보여주게 하는 역할(UI)
  3. Controller는 뷰에서 일어나는 액션과 이벤트의 input 값을 가지고 가공을 거친 후 Model에게 값을 넘겨서 update 및 처리를 한다. 다시 값을 반환 했다면 View가 확인 할 수 있도록 다시 데이터를 가공하고 View에게 전달한다.

참고
https://www.youtube.com/watch?v=Rr6lHwzgvOI


ORM

Object–relational mapping(ORM, O/RM, and O/R mapping tool) in computer science is a programming technique for converting data between incompatible type systems using object-oriented programming languages.

쉽게 말하자면 객체와 관계형 데이터베이스 사이의 프로그래밍 언어 관점에서 맞춰주는 통역사라고 볼 수 있다.

참고
https://sequelize.org/master/index.html

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

-> Node.js ORM

npm 설치

npm install --save sequelize //최신버전 v6

참조
https://sequelize.org/master/manual/migrations.html

Just like you use version control systems such as Git to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.

-> 데이터 베이스의 변경 사항을 추적(스키마 변경에 따른 데이터 이주(migration)를 뜻합니다.)

스키마 변경이 있을 때마다 마이그레이션을 실행해줘야 합니다.

To install the Sequelize CLI:

npm install --save-dev sequelize-cli

To create an empty project you will need to execute init command

cli를 통해 orm을 사용하도록 bootstraping(프로젝트 초기 단계를 자동으로 설정할 수 있도록 도와주는 일)을 해줘야한다.

npx sequelize-cli init

시퀄라이즈 cli 공식문서 (명령어등등)
https://github.com/sequelize/cli


  • 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개의 파일이 생성된다.

{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "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"
  }
}

생성된 json의 내용에서 database_development부분이 기본 적으로 mysql에서 쓰여지는 환경이다.

Once you have properly configured CLI config file you are ready to create your first migration. It's as simple as executing a simple command.

name: the name of the model;
attributes: the list of model attributes.

npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string

원하는 옵션 값으로 설정 해 줄 수 있다.

npx sequelize-cli model:generate --name url --attributes title:string,visits:string,email:string

This will:
Create a model file user in models folder;
Create a migration file with name like XXXXXXXXXXXXXX-create-user.js in migrations folder.

Note: Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database.

Model 파일은 모델 파일에서만 쓰는 테이블 표현인 반면에 migration으로 만들어지는 내용은 Cli에 사용되어진 변경 사항이다.

we haven't inserted anything into the database. We have just created required model and migration files for our first model User. Now to actually create that table in database you need to run db:migrate command.

실제 테이블에 데이터베이스를 생성하려면 db:migrate를 실행해야한다.

npx sequelize-cli db:migrate

node.js 에서 HTTP 요청을 하기 위해 request 라는 라이브러리를 사용하였습니다. 비슷한 일을 하는 라이브러리로는 axios, node-fetch 등이 있습니다. node.js 내장 http, https 모듈을 이용해 이를 직접 구현할 수 있습니다.

request
https://github.com/request/request

axios
https://github.com/axios/axios

node-fetch
https://github.com/node-fetch/node-fetch


정리되어진 블로그

https://medium.com/graphql-seoul/%EB%B2%88%EC%97%AD-%EB%A7%88%EC%9D%B4%EA%B7%B8%EB%A0%88%EC%9D%B4%EC%85%98%EA%B3%BC-sequelize-cli-%ED%8A%9C%ED%86%A0%EB%A6%AC%EC%96%BC-3926c0a9eae6

https://velog.io/@dlrbwls0302/TIL-SequelizeShortly-mvc-%EC%BD%94%EB%93%9C-%EB%B6%84%EC%84%9D


더 공부해야할 것

생활코딩 mvc부분 동영상 강의와 함께 보기
https://opentutorials.org/module/327/3828

profile
til' CTF WIN

0개의 댓글