There are so many architectures in the developers' world. Layered, Component, etc... I would like to discuss most popular architecture called MVC





MVC in Brief

MVC contains with -> Model, Value and Controller

Model
represent data in the code.
work with data -> fetch, save

View
What the user sees.
Rendering the right contact and send to the user

Controller
connection point to models and views. (middleman)
in NodeJS-> Set routes, split across middleware functions


Adding a Model

const products = [];

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

  save() {
      //in here also values can be assign-> this.id=Math.random().toString()
    products.push(this);
//this refer the object created in the class = Product
  }

  static fetchAll() {
    return products;
  }
};


Adding a Controller

--------------------
in routs -> shop.js
--------------------

const productController = require("../controllers/products");
// add a controller to handle the route fuctions

router.get("/", productController.getProducts);

---------------------------
in controllers->products.js
---------------------------

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

exports.postAddProduct = (req, res, next) => {

  const product = new Product(req.body.title);
  product.save();
  res.redirect("/");
};


exports.getProducts = (req, res, next) => {
  const products = Product.fetchAll();
  res.render("shop", {
    prods: products,
  });       //add-product.ejs page [This is our View]
};


[router routs to the specified URL and the function handles by the controller]