【nestjs】一般学习路线

发布于:2025-05-10 ⋅ 阅读:(8) ⋅ 点赞:(0)

nestjs中文文档

其实几个月前也对nestjs进行了学习,前前后后看了很多文档、博客,另外也找了相应的代码看了,但最后也还是一知半解,只是知道大概怎么写,怎么用。

这次下定决心再次看一遍,从代码学习到文档又梳理了一遍,总算是有点眉目,把心得分享一下。

一、首先找一个开源代码,尝试跑起来并深度阅读,打console了解和熟悉每个模块、每一步的具体功能。

我这边参考了nest-admin
按照作者的逻辑,安装MySql 、Redis 环境,将db/kapok.sql导入sql中,运行就可以。
在这里插入图片描述
在这里插入图片描述
作为一个前端要按照后端思维去理解nest,显然有些困难,因此细致的注释和console是很必要的。

二、如果你对工程已经熟悉了,那么第二步就是去阅读中文文档,这次一定要细致的阅读,并从文档中找到程序中的类比。

在这里插入图片描述
在这里插入图片描述

三、紧接着就是对工程进行模块新增了,参考其他模块我写了一个test模块。

在这里插入图片描述
在这里插入图片描述

总得来说,一个增删改查的页面会包含 dto、entities、controller、service、module。
entities:包含了当前功能的字段类型、表设计。
dto:包含了service中接口要使用的具体参数定义,明确了各个参数的限制类型,swigger等。
service:取dto中的文件信息用在相应的方法中,用于接收参数并利用typeOrm进行数据库具体方法的处理。
controller:使用Service中的方法,定义了各种get、post、delete、put等接口调用。
module: 承载service、entities、controller,最终作为统一出口文件,让根文件(app.module.ts)去引用。

// test.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm'
import { ApiProperty } from '@nestjs/swagger'
import { $enum } from 'ts-enum-util'

import { StatusValue } from '../../../common/enums/common.enum'

@Entity('sys_post1')
export class TestEntity {
  @ApiProperty({ description: 'id' })
  @PrimaryGeneratedColumn({ type: 'bigint' })
  id: string

  @ApiProperty({ description: '岗位编码' })
  @Column({ type: 'varchar', length: 50, comment: '岗位编码' })
  code: string

  @ApiProperty({ description: '岗位名称' })
  @Column({ type: 'varchar', length: 50, comment: '岗位名称' })
  name: string

  @ApiProperty({ description: '状态', enum: $enum(StatusValue).getValues() })
  @Column({ type:  'tinyint', default: StatusValue.NORMAL, comment: '岗位状态,1-有效,0-禁用' })
  status: StatusValue

  @ApiProperty({ description: '备注' })
  @Column({ type: 'text',default: null, comment: '备注' })
  remark: string

  @ApiProperty({ description: '排序' })
  @Column({ name: 'order_num', type: 'int', comment: '排序', default: 0 })
  orderNum: number

  @ApiProperty({ description: '创建时间' })
  @CreateDateColumn({ type: 'timestamp', name: 'create_date', comment: '创建时间' })
  createDate: Date
}
// create-test.dto.ts
import { ApiProperty } from '@nestjs/swagger'
import { IsString, IsNotEmpty, IsNumber, Min, IsOptional, MinLength, MaxLength } from 'class-validator'

export class CreateTestDto {
  @ApiProperty({ description: '岗位编码' })
  @IsString({ message: 'code 类型错误,正确类型 string' })
  @IsNotEmpty({ message: 'code 不能为空' })
  @MaxLength(50, { message: '岗位编码最多50个字符' })
  readonly code: string

  @ApiProperty({ description: '岗位名称' })
  @IsString({ message: 'name 类型错误, 正确类型 string' })
  @IsNotEmpty({ message: 'name 不能为空' })
  @MinLength(2, { message: '岗位名称至少2个字符' })
  @MaxLength(50, { message: '岗位名称最多50个字符' })
  readonly name: string

  @ApiProperty({ description: '排序' })
  @IsNumber({}, { message: 'orderNum 类型错误, 正确类型 number ' })
  @Min(0)
  readonly orderNum: number

  @ApiProperty({ description: '备注' })
  @IsString({ message: 'remark 类型错误, 正确类型 string' })
  @IsOptional()
  readonly remark: string
}
// test.service.ts
import { Injectable } from '@nestjs/common'
import { InjectRepository, InjectEntityManager } from '@nestjs/typeorm'
import { Repository, Like, EntityManager } from 'typeorm'
import { plainToInstance } from 'class-transformer'

import { ResultData } from '../../common/utils/result'
import { AppHttpCode } from '../../common/enums/code.enum'

import { TestEntity } from './entities/test.entity'

import { FindTestListDto } from './dto/findTestList.dto'
import { CreateTestDto } from './dto/create-test.dto'
import { UpdateTestDto } from './dto/update-test.dto'

@Injectable()
export class TestService {
  constructor(
    @InjectRepository(TestEntity)
    private readonly postRepo: Repository<TestEntity>,
    @InjectEntityManager()
    private readonly postManager: EntityManager,
  ) {}

  /** 创建岗位 */
  async create(dto: CreateTestDto): Promise<ResultData> {
    const existing = await this.postRepo.findOne({ where: { code: dto.code, name: dto.name } })
    if (existing) return ResultData.fail(AppHttpCode.POST_REPEAT, '当前岗位名称与编码已存在,请修改后重新创建')
    const post = plainToInstance(TestEntity, dto)
    const res = await this.postManager.transaction(async (transactionalEntityManager) => {
      return await transactionalEntityManager.save<TestEntity>(post)
    })
    if (!res) ResultData.fail(AppHttpCode.SERVICE_ERROR, '创建失败,请稍后重试')
    return ResultData.ok(res)
  }

  /** 更新岗位 */
  async update(dto: UpdateTestDto): Promise<ResultData> {
    const existing = await this.postRepo.findOne({ where: { id: dto.id } })
    if (!existing) return ResultData.fail(AppHttpCode.POST_NOT_FOUND, '岗位不存在或已被删除,请修改后重新添加')
    const { affected } = await this.postManager.transaction(async (transactionalEntityManager) => {
      return await transactionalEntityManager.update<TestEntity>(TestEntity, dto.id, dto)
    })
    if (!affected) return ResultData.fail(AppHttpCode.SERVICE_ERROR, '更新失败,请稍后尝试')
    return ResultData.ok()
  }

  /** 删除岗位 */
  async delete(id: string): Promise<ResultData> {
    const existing = await this.postRepo.findOne({ where: { id } })
    if (!existing) return ResultData.fail(AppHttpCode.POST_NOT_FOUND, '岗位不存在或已被删除')
    const { affected } = await this.postManager.transaction(async (transactionalEntityManager) => {
      return await transactionalEntityManager.delete<TestEntity>(TestEntity, id)
    })
    if (!affected) return ResultData.fail(AppHttpCode.SERVICE_ERROR, '删除部门失败,请稍后尝试')
    return ResultData.ok()
  }

  /** 查询岗位 */
  async findList(dto: FindTestListDto): Promise<ResultData> {
    const { size, page, name, code, status } = dto
    const where = {
      ...(!!name ? { name: Like(`%${name}%`) } : null),
      ...(!!code ? { code: Like(`%${code}%`) } : null),
      ...(![null, undefined].includes(status) ? { status } : null),
    }
    const posts = await this.postRepo.findAndCount({
      where,
      order: { orderNum: 'DESC', id: 'DESC', createDate: 'DESC' },
      skip: size * (page - 1),
      take: size,
    })
    return ResultData.ok({ list: posts[0], total: posts[1] })
  }
  /** 查询单个岗位信息 */
  async findOne(id: string): Promise<ResultData> {
    const post = await this.postRepo.findOne({ where: { id } })
    return ResultData.ok(post)
  }
}

// test.controller.ts
import { Controller, Post, Body, Delete, Get, Put, Param, Query } from '@nestjs/common'
import { ApiOperation, ApiTags, ApiBearerAuth } from '@nestjs/swagger'

import { ApiResult } from '../../common/decorators/api-result.decorator'
import { ResultData } from '../../common/utils/result'

import { TestEntity } from './entities/test.entity'
import { TestService } from './test.service'

import { FindTestListDto } from './dto/findTestList.dto'
import { CreateTestDto } from './dto/create-test.dto'
import { UpdateTestDto } from './dto/update-test.dto'

@ApiTags('岗位模块')
@ApiBearerAuth()
@Controller('test')
export class TestController {
  constructor(private readonly testService: TestService) {}

  @Post()
  @ApiOperation({ summary: '创建岗位' })
  @ApiResult(TestEntity)
  async create(@Body() dto: CreateTestDto): Promise<ResultData> {
    return this.testService.create(dto)
  }

  @Put()
  @ApiOperation({ summary: '岗位更新' })
  @ApiResult()
  async update(@Body() dto: UpdateTestDto): Promise<ResultData> {
    return this.testService.update(dto)
  }

  @Get('list')
  @ApiOperation({ summary: '查询岗位列表' })
  @ApiResult(TestEntity, true)
  async find(@Query() dto: FindTestListDto): Promise<ResultData> {
    return this.testService.findList(dto)
  }

  @Get(':id')
  @ApiOperation({ summary: '查询岗位详情' })
  @ApiResult(TestEntity)
  async findOne(@Param('id') id: string): Promise<ResultData> {
    return this.testService.findOne(id)
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除岗位' })
  @ApiResult()
  async delete(@Param('id') id: string): Promise<ResultData> {
    return this.testService.delete(id)
  }
}

// test.module.ts
import { Module } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'

import { TestEntity } from './entities/test.entity'
import { TestService } from './test.service'
import { TestController } from './test.controller'

@Module({
  imports: [TypeOrmModule.forFeature([TestEntity])],
  providers: [TestService],
  controllers: [TestController]
})
export class TestModule {}

写在后面的话:

前端学习后端思维绝非易事,一定要脚踏实地,不可心浮气躁。

后面想再出一个更细的nestjs模块解释,欢迎关注。


网站公告

今日签到

点亮在社区的每一天
去签到