DEV Community

Cover image for Nestjs Course - Lesson 02 - Introduction to the MVC pattern
NextjsVietnam
NextjsVietnam

Posted on

Nestjs Course - Lesson 02 - Introduction to the MVC pattern

Source Code

Lesson 02

  1. Preliminary design requirements analysis
  2. Setting up the project structure
  3. Overview of classes in the MVC model and code practice

Request parsing

Sitemap

image

Functional details

image

Database Design

image

Set up project structure

  1. Create a new project with NestJS
  2. Project folder structure according to module structure and MVC model
  3. Debug NestJS project with VSCode

Create a new project with NestJS

nest new nestjs-tutorial-2023 --skip-install
cd nestjs-tutorial-2023
npm i
Enter fullscreen mode Exit fullscreen mode

image

After initializing the project, the project's directory tree structure will look like the image below:

image

Project directory structure according to the module structure and MVC model

  1. Install NestJS to support template Engine EJS

Let's go back a bit with the architecture of expressjs, you need to set some parameters as follows:

  • Template Engine: some popular template engines like pug, ejs, hbs
  • Static Assets: folder containing static files such as css, js, images of the website
const express = require("express");
const app = express();
const port = process.env.PORT || 1337;
const path = require("path");

// static assets
const publicAssetsPath = path.resolve(process.cwd(), "public");
// using express static middleware
app.use("/public", express.static(publicAssetsPath));
// Your asset will be placed at : http://localhost:1337/public/assets/main.css

// select view engine is ejs
app.set("view engine", "ejs");

// set view folder
const viewsPath = process.cwd() + "/views";
app.set("views", [viewsPath]);

// global variable through app
app.locals = {
   title: "MVC Tutorial",
};

// home page
app.get("/", (req, res) => {
   res.render("index", { heading: "Home page" });
});

app.listen(port, () => {
   console.log(`Example app listening at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

And in NestJS, how will we do it?

npm install --save @nestjs/serve-static
npm i --save ejs
Enter fullscreen mode Exit fullscreen mode
// src/app.module.ts
import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { ServeStaticModule } from "@nestjs/serve-static";
import { join } from "path";

@Module({
   imports: [
     // public folder
     ServeStaticModule.forRoot({
       rootPath: join(process.cwd(), "public"),
       // Your asset will be placed at : http://localhost:1337/public/assets/main.css
       serveRoot: "/public",
     }),
   ],
   controllers: [AppController],
   providers: [AppService],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode
// src/main.ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { NestExpressApplication } from "@nestjs/platform-express";
import { join } from "path";

async function bootstrap() {
   const app = await NestFactory.create<NestExpressApplication>(AppModule);

   // app.useStaticAssets(join(process.cwd(), 'public'));
   app.setViewEngine("ejs");
   app.setBaseViewsDir([join(process.cwd(), "views")]);

   await app.listen(3000);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode
// src/app.controller.ts

import { Controller, Get, Render } from "@nestjs/common";
import { AppService } from "./app.service";

@Controller()
export class AppController {
   constructor(private readonly appService: AppService) {}

   @Get()
   @Render("index")
   homePage() {
     return {};
   }
}
Enter fullscreen mode Exit fullscreen mode

views/index.ejs

<!DOCTYPE html>
<html lang="en">
   <head>
     <meta charset="UTF-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <title><%= title %></title>
     <link rel="stylesheet" href="/public/assets/main.css" />
   </head>
   <body>
     <h1><%= title %></h1>
     <img
       src="/public/assets/nestjs-tutorial-2023.png"
       alt="NestJS Tutorial 2023"
     />
     <script src="/public/assets/main.js"></script>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

And here is what you get

image

References

Top comments (0)