Skip to main content

100. Basics

Intro

  • Nest.Js official introduction
    • Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications.
    • It uses progressive JavaScript, is built with and fully supports TypeScript.
  • Nest.js is configurable
    • ex: by default uses express but can work with fastify http server
  • you can use nest.js to mainly build
    • rest.api
    • micro-services
    • web sockets
    • and graphQL
  • nest cli
    • nest has a cli, that you can use to create, run nest projects
    • can be used to create files
    • run nest --help for more.
  • Nest Building Blocks
    • nest has many building blocks that serve specific purposes and play a crucial role in the overall architecture of an application,
    • Fundamentals building blocks
    • More Building Blocks
      • Exception filters
      • Guards
      • Pipes
      • Interceptors
      • Middlewares

Nest CLI

Build & Run

npm i -g @nestjs/cli
nest new project-name

cd project-name
npm run start
  • nest has development mode
    • reloads on file changes
    • automatic re-build
npm run start:dev

# To speed up the development process (x20 times faster builds), you can use the SWC builder by passing the -b swc flag to the start script, as follows npm
npm run start -- -b swc

File Generation

  • Generating nest building blocks(modules, components, services…)
nest g co component-name

#with not test
nest g co componet-name --no-spec

nest g mo module-name

nest g s service-name

Crud Generator

  • CRUD generator | NestJS - A progressive Node.js framework
  • When working on a new feature i.e Product, instead of creating each nest building blocks, you can use nest g resource.
  • nest g resource command not only generates all the NestJS building blocks (module, service, controller classes) but also an entity class, DTO classes as well as the testing (.spec) files.
nest g resource resource-name

#ex:
nest g resource users

nest g resource users --no-spec #to avoid test files

nest crud generator also works for graphql and microservice projects

Folder Structure

  • In Nest.js, there isn't a strict folder structure that you must adhere to. However, it's common to follow a modular approach when organizing your codebase, especially for larger projects. Here's a suggested folder structure for a "users" feature:
src/
└── users/
├── dto/
│ ├── create-user.dto.ts
│ └── update-user.dto.ts
├── entities/
│ └── user.entity.ts
├── controllers/
│ └── users.controller.ts
├── services/
│ └── users.service.ts
├── modules/
│ └── users.module.ts