Nestjs project demo (with github code address)

Foreword:

This .md blog is a structural review of my study of the nest.js framework in the past two weeks. It aims to talk about a general project structure, what the basic structure and code are used for, and it cannot be done from 0 basics to complete completion Initialization of Nest.js project.

Project features:

Core technology stack

Nestjs + TypeORM + MySQL + Jwt + Docker

Function

Basic one-to-one, many-to-many, one-to-many database table connection, database linked list query, complete crud of user class, paging query configuration, jwt authentication, password encryption processing.

Aimed at a relatively complete writing of the node back-end code

Project Introduction

Project directory

image.png

Document introduction

configuration file

image.png
I won’t go into too much detail about these files. Anyone with a background in frameworks should know what they do. They are basically configuration files of the project framework.

hub file

image.png

main.ts

Mainly responsible for framework agent startup server

app.module.ts

The hub of the code, completes various connection configurations of **database connection**

Database and interface files

The structure is similar to the structure of the springboot framework. The code logic has a relatively clear classification.
The user has a relatively standard file structure. Let's take a user class as an example:

File Directory

image.png

xxx.module.ts

The hub connecting user class interfaces

@Module({
    
    
  imports: [
    TypeOrmModule.forFeature([User, Logs, Roles]),
    LoggerModule.forRoot({
    
    
      pinoHttp: {
    
    
        transport: {
    
    
          target: 'pino-pretty', //打印日志样式优化
          options: {
    
    
            colorize: true,
          },
        },
      },
    }),
  ],
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {
    
    }

xxx.entity.ts

Create database table files

import {
    
    
  Column,
  Entity,
  PrimaryGeneratedColumn,
  OneToMany,
  ManyToMany,
  JoinTable,
  OneToOne,
} from 'typeorm';
import {
    
     Logs } from '../logs/logs.entity';
import {
    
     Roles } from 'src/roles/roles.entity';
import {
    
     Profile } from './profile.entity';
// import { Roles } from '../roles/roles.entity';

@Entity()
export class User {
    
    
  @PrimaryGeneratedColumn()
  id: number;

  @Column({
    
     unique: true }) //设置唯一账号
  username: string;

  @Column()
  password: string;

  // typescript -> 数据库 关联关系 Mapping,
  //一对多
  @OneToMany(() => Logs, (logs) => logs.user, {
    
     cascade: true })
  logs: Logs[];

  //多对多
  @ManyToMany(() => Roles, (roles) => roles.users, {
    
     cascade: ['insert'] })
  @JoinTable({
    
     name: 'users_roles' })
  roles: Roles[];

  //, { cascade: true }设置连表更新 一对一
  @OneToOne(() => Profile, (profile) => profile.user, {
    
     cascade: true })
  profile: Profile;
}

xxx.controller.ts (controller layer, control layer)

For the control of the specific business module process , the interface request entry , the controller layer mainly calls the interface in the Service layer to control the specific business process, and the configuration of the control is also carried out in the configuration file.

@Controller('user')
@UseFilters(new TypeormFilter()) //错误 信息返回封装
@UseGuards(JwtGuard) //守卫,设置token
export class UserController {
    
    
  constructor(
    private userService: UserService,
    private configService: ConfigService,
    private logger: Logger,
  ) {
    
    
    this.logger.log('User');
  }

  @Get()
  getUsers(@Query() query: UserQeury): any {
    
    
    //分页查询
    return this.userService.findAll(query);
  }
  //
  @Post()
  addUser(@Body(CreateUserPipe) dto: CreateUserDto): any {
    
    
    //@Body data参数
    // todo 解析Body参数
    const user = dto as User;
    return this.userService.create(user);
  }
  @Patch('/:id')
  updateUser(@Body() dto: any, @Param('id') id: number): any {
    
    
    // todo 传递参数id
    // todo 异常处理
    const user = dto as User;
    return this.userService.update(id, user);
  }

  @UseGuards(AdminGuard) //管理员守卫,不是id为2的不行
  @Delete('/:id')
  deleteUser(@Param('id') id: number): any {
    
    
    // todo 传递参数id
    return this.userService.remove(id);
  }

  //ParseIntPipe 管道,将 id 转换成数字形式
  @Get('/findAddProfile')
  findAddProfile(@Query('id', ParseIntPipe) query: any): any {
    
    
    return this.userService.findAddProfile(query.id);
  }
}

xxx.service.ts (service layer, business layer)

The logical application design of the interface business module , like the DAO layer, first designs the interface, then creates the class to be implemented, and then configures the association of its implementation in the configuration file. Next, you can call the interface in the service layer to process the business logic application.

dto (entity class, request class)

Tool files

guards

image.png
What is completed is the encapsulation of the global jwt tool and the encapsulation of the specified administrator jwt authentication function tool.

filters (filter, interface return package)

Encapsulation and configuration of interface data return type , encapsulation of request log function

test (test file)

image.png

enum (data enumeration)

Project operation

Operating environment

  1. node environment
  2. docker environment
  3. mysql environment

These are the important environments for the project to run.
Regarding the problems encountered in installing the docker environment, you can read a blog I wrote:
https://blog.csdn.net/Azbtt/article/details/132182380

Run configuration

Before running the project, please configure the local database environment by yourself, and modify the configuration files in the project root directory: .env, .env.development(development), .env.production(production).
It is recommended to use node14 LTSinstallation dependencies:

npm i

Run command

Run the project:

npm run start:dev

Github address:

https://github.com/wzz778/NestjsProjectDemo

Learning video address: MOOC practical courses - real project drills to improve personal skills

Guess you like

Origin blog.csdn.net/Azbtt/article/details/132308786