10.17 TIL. [아키텍처 패턴] MVC

이정민·2022년 11월 17일
0

MVC(Model- View- Controller)는 소프트웨어 디자인 패턴으로

Model

  1. 모델의 상태에 변화가 있을 때 Controller 와 View에 통보해서 View는 최신의 결과를 보여주고 Controller는 Model의 변화에 따른 적용 가능한 명령을 추가, 제거, 수정할 수 있다.
  2. 어플리케이션의 데이터를 나타낸다.
  3. “무엇”을 할 것인지

View

  1. 텍스트, 체크박스 항목과 같은 사용자 인터페이스 요소를 나타낸다.
  2. 사용자가 볼 결과물을 생성하기 위해 모델로 부터 정보를 얻어온다.
  3. “무엇”을 보여주는 역할

Controller

  1. 데이터와 비지니스 로직 사이의 상호 동장을 관리한다.
  2. 모델에 명령을 보냄으로서 모델의 상태를 변경할 수 있다.
  3. 모델이 “어떻게” 처리할 지 알려주는 역할
class HttpError extends Error {
  constructor(message, errorCode) {
    super(message); // Add a "message" property
    this.code = errorCode; //Adds a "code" property
  }
}
module.exports = HttpError;

모델의 예시

const HttpError = require("../models/http-error");
const DUMMY_PLACES = [
  {
    id: "p1",
    title: "Empire State Building",
    description: "One of the most famous building in the world",
    location: {
      lat: 40.7484474,
      lng: -73.9871516,
    },
    address: "20 W 34th St, New York, NY 10001",
    creator: "u1",
  },
];

const getPlaceById = (req, res, next) => {
  const placeId = req.params.pid;

  const place = DUMMY_PLACES.find((p) => {
    return p.id === placeId;
  });

  if (!place) {
    throw new HttpError("Could not find a place for the provided id", 404);
  }

  res.json({ place: place });
};

const getPlaceByUserId = (req, res, next) => {
  const userId = req.params.uid;
  const place = DUMMY_PLACES.find((p) => {
    return p.creator === userId;
  });
  if (!place) {
    return next(
      new HttpError("Could not find a place for the provided user id", 404)
    );
  }

  res.json({ place });
};

const createPlace = (req, res, next) => {};

exports.getPlaceById = getPlaceById;
exports.getPlaceByUserId = getPlaceByUserId;
exports.createPlace = createPlace;

controller의 예시

출처: https://ko.wikipedia.org/wiki/모델-뷰-컨트롤러

0개의 댓글