/node-mvc-template

Example template for node Model-View-Controller Architecture for an online shop

Primary LanguageHTML

Node.js MVC Template

Basic MVC file structure

app.js
|-routes
    |-shop.js
|-models
    |-product.js
|-views
    |-shop.ejs
|-controllers
    |-products.js

M = Model

  • what : Models represent data in your code, ES6 classes
  • where: in /models
  • format: product.js
module.exports = class Product {
  constructor(title) {
    this.title = title;
  }

  // class functions
  save() { ... }

  fetchAll() { ... }
};

V = View

  • what: What user sees, UI
  • where: in /views
  • format: HTML or its variation with templating engines

C = Controller

  • what: logic to connect models and views, API requests and routes

  • where: split across middleware functions

  • format:

    • app.js
    const publicRoutes = require("./routes/shop");
    
    app.use(publicRoutes);
    
    • /routes/shop.js
      const express = require("express");
      const router = express.Router();
      const productsController = require("../controllers/products");
    
      router.get("/", productsController.getProducts);
    
      module.exports = router;
    
    
    • /controllers/products.js
      const Product = require("../models/product");
    
      exports.getProducts = (req, res, next) => {
      // second argument is callback as the action is asynchronous
          Product.fetchAll(products => {
              res.render("shop", {
                  prods: products,
                  pageTitle: "Shop",
                  path: "/",
              });
          });
      };