간단한 MVC 패턴 활용하기

이율곡·2023년 1월 15일
0

Node js

목록 보기
8/26
post-thumbnail

MVC모델이란?

MVC 모델이란 Model, View, Controller의 약자로 웹을 개발할 때 세 가지의 역할로 구분해서 개발하는 방법론이다.


Model


Model의 파일 구성 예시

Model의 역할은 데이터를 관리하는 역할이다. 주로 데이터베이스와 연결하여 사용되며 Cotroller가 요청한 값을 데이터베이스에서 찾아서 돌려주는 역할을 한다.

View


View의 파일 구성 예시

View는 말 그대로 보여주는 역할이다. 화면을 담당하며 Controller의 요청에 맞는 화면을 제공한다.

Controller


Controller의 파일 구성 예시

Controller는 사용자의 요청을 처리하는 역할이다. 그래서 Controller를 통해 Model에 값을 요청하거나 View를 통해 화면을 보여주는 것도 전부 Controller의 일이다.


활용해보기

Model

Model은 앞에서도 말했듯이 데이터를 담당하는 역할이다. 코드를 보면

const fs = require("fs");
const path = require("path");

const p = path.join(
  path.dirname(require.main.filename),
  "data",
  "products.json"
);

const getProductsFormFile = (cb) => {
  fs.readFile(p, (err, fileContent) => {
    if (err) {
      cb([]);
    } else{
      cb(JSON.parse(fileContent));
    }
  });
};

module.exports = class Product {
  constructor(t) {
    this.title = t;
  }

  save() {
    getProductsFormFile((products) => {
      products.push(this);
      fs.writeFile(p, JSON.stringify(products), (err) => {
        console.log(err);
      });
    });
  }
};

이와 같은데 중요한 부분은 class Product 부분이다. 이곳에서 save함수를 활용하여 product 배열에 값을 넣어 JSON 파일을 만들어 관리하는 역할을 한다.

View

View는 화면을 보여주는 역할이다.

<%- include('includes/add-product-head.ejs')%>
</head>

<body>
    <%- include('includes/navigation.ejs') %>
    <main>
        <form class="product-form" action="/admin/add-product" method="POST">
            <div class="form-control">
                <label for="title">Title</label>
                <input type="text" name="title" id="title">
            </div>

            <button class="btn" type="submit">Add Product</button>
        </form>
    </main>

<%- include('includes/end.ejs') %>

Controller에서 get형식으로 add-product라는 요청이 왔을 시 위의 화면이 출력된다. ejs 템플릿을 활용하기 때문에 include로 레이아웃이 나뉜 걸 확인할 수 있다.

Controller

Controller는 사용자의 요청을 처리하는 역할이다.

const Product = require("../models/product");

exports.getAddProduct = (req, res, next) => {
  res.render("add-product", {
    pageTitle: "Add Product",
    path: "/admin/add-product",
    formsCSS: true,
    productCSS: true,
    activeAddProduct: true,
  });
};

exports.postAddProdoct = (req, res, next) => {
  const product = new Product(req.body.title);
  product.save();
  res.redirect("/");
};

exports.getProducts = (req, res, next) => {
  Product.fetchAll((products) => {
      res.render("shop", {
        prods: products,
        pageTitle: "Shop",
        path: "/",
        hasProducts: products.length > 0,
        activeShop: true,
        productCSS: true,
      })
  });
};

Node js에서 Controller는 Service를 처리하는 일이다. Routes에서 경로설정과 요청에 따른 Controller를 동작시키는 형태로 돌아가는 것 같다.

router.get("/add-product", productsController.getAddProduct);

위와 같이 Routes에서 add-product로 get요청이 오면 그 안에 있는 productsController에 있는 getAddProduct가 응답하는 형식으로 Node js의 MVC 패턴이 이루어진다.

정리하기

MVC 패턴은 각각의 역할을 이해하고 있다면 웹 서비스를 만들 때 안전하고 편하게 만들 수 있다. 이번에는 간단하게 만들었기 때문에 아직 가야 할 길이 많이 남았지만, 꽤나 많이 걸어온 것 같다. 앞으로 데이터베이스 연결이나 고급개발을 들어가기 위해선 꼭 복습하고 이해하고 넘어가야겠다.

profile
음악을 좋아하는 사람이 음악을 만들 듯, 개발을 좋아하게 될 사람이 쓰는 개발이야기

0개의 댓글