【nestjs】一般学习蹊径

[复制链接]
发表于 2025-9-13 17:00:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
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)去引用。
  1. // test.entity.ts
  2. import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm'
  3. import { ApiProperty } from '@nestjs/swagger'
  4. import { $enum } from 'ts-enum-util'
  5. import { StatusValue } from '../../../common/enums/common.enum'
  6. @Entity('sys_post1')
  7. export class TestEntity {
  8.   @ApiProperty({ description: 'id' })
  9.   @PrimaryGeneratedColumn({ type: 'bigint' })
  10.   id: string
  11.   @ApiProperty({ description: '岗位编码' })
  12.   @Column({ type: 'varchar', length: 50, comment: '岗位编码' })
  13.   code: string
  14.   @ApiProperty({ description: '岗位名称' })
  15.   @Column({ type: 'varchar', length: 50, comment: '岗位名称' })
  16.   name: string
  17.   @ApiProperty({ description: '状态', enum: $enum(StatusValue).getValues() })
  18.   @Column({ type:  'tinyint', default: StatusValue.NORMAL, comment: '岗位状态,1-有效,0-禁用' })
  19.   status: StatusValue
  20.   @ApiProperty({ description: '备注' })
  21.   @Column({ type: 'text',default: null, comment: '备注' })
  22.   remark: string
  23.   @ApiProperty({ description: '排序' })
  24.   @Column({ name: 'order_num', type: 'int', comment: '排序', default: 0 })
  25.   orderNum: number
  26.   @ApiProperty({ description: '创建时间' })
  27.   @CreateDateColumn({ type: 'timestamp', name: 'create_date', comment: '创建时间' })
  28.   createDate: Date
  29. }
复制代码
  1. // create-test.dto.ts
  2. import { ApiProperty } from '@nestjs/swagger'
  3. import { IsString, IsNotEmpty, IsNumber, Min, IsOptional, MinLength, MaxLength } from 'class-validator'
  4. export class CreateTestDto {
  5.   @ApiProperty({ description: '岗位编码' })
  6.   @IsString({ message: 'code 类型错误,正确类型 string' })
  7.   @IsNotEmpty({ message: 'code 不能为空' })
  8.   @MaxLength(50, { message: '岗位编码最多50个字符' })
  9.   readonly code: string
  10.   @ApiProperty({ description: '岗位名称' })
  11.   @IsString({ message: 'name 类型错误, 正确类型 string' })
  12.   @IsNotEmpty({ message: 'name 不能为空' })
  13.   @MinLength(2, { message: '岗位名称至少2个字符' })
  14.   @MaxLength(50, { message: '岗位名称最多50个字符' })
  15.   readonly name: string
  16.   @ApiProperty({ description: '排序' })
  17.   @IsNumber({}, { message: 'orderNum 类型错误, 正确类型 number ' })
  18.   @Min(0)
  19.   readonly orderNum: number
  20.   @ApiProperty({ description: '备注' })
  21.   @IsString({ message: 'remark 类型错误, 正确类型 string' })
  22.   @IsOptional()
  23.   readonly remark: string
  24. }
复制代码
  1. // test.service.ts
  2. import { Injectable } from '@nestjs/common'
  3. import { InjectRepository, InjectEntityManager } from '@nestjs/typeorm'
  4. import { Repository, Like, EntityManager } from 'typeorm'
  5. import { plainToInstance } from 'class-transformer'
  6. import { ResultData } from '../../common/utils/result'
  7. import { AppHttpCode } from '../../common/enums/code.enum'
  8. import { TestEntity } from './entities/test.entity'
  9. import { FindTestListDto } from './dto/findTestList.dto'
  10. import { CreateTestDto } from './dto/create-test.dto'
  11. import { UpdateTestDto } from './dto/update-test.dto'
  12. @Injectable()
  13. export class TestService {
  14.   constructor(
  15.     @InjectRepository(TestEntity)
  16.     private readonly postRepo: Repository<TestEntity>,
  17.     @InjectEntityManager()
  18.     private readonly postManager: EntityManager,
  19.   ) {}
  20.   /** 创建岗位 */
  21.   async create(dto: CreateTestDto): Promise<ResultData> {
  22.     const existing = await this.postRepo.findOne({ where: { code: dto.code, name: dto.name } })
  23.     if (existing) return ResultData.fail(AppHttpCode.POST_REPEAT, '当前岗位名称与编码已存在,请修改后重新创建')
  24.     const post = plainToInstance(TestEntity, dto)
  25.     const res = await this.postManager.transaction(async (transactionalEntityManager) => {
  26.       return await transactionalEntityManager.save<TestEntity>(post)
  27.     })
  28.     if (!res) ResultData.fail(AppHttpCode.SERVICE_ERROR, '创建失败,请稍后重试')
  29.     return ResultData.ok(res)
  30.   }
  31.   /** 更新岗位 */
  32.   async update(dto: UpdateTestDto): Promise<ResultData> {
  33.     const existing = await this.postRepo.findOne({ where: { id: dto.id } })
  34.     if (!existing) return ResultData.fail(AppHttpCode.POST_NOT_FOUND, '岗位不存在或已被删除,请修改后重新添加')
  35.     const { affected } = await this.postManager.transaction(async (transactionalEntityManager) => {
  36.       return await transactionalEntityManager.update<TestEntity>(TestEntity, dto.id, dto)
  37.     })
  38.     if (!affected) return ResultData.fail(AppHttpCode.SERVICE_ERROR, '更新失败,请稍后尝试')
  39.     return ResultData.ok()
  40.   }
  41.   /** 删除岗位 */
  42.   async delete(id: string): Promise<ResultData> {
  43.     const existing = await this.postRepo.findOne({ where: { id } })
  44.     if (!existing) return ResultData.fail(AppHttpCode.POST_NOT_FOUND, '岗位不存在或已被删除')
  45.     const { affected } = await this.postManager.transaction(async (transactionalEntityManager) => {
  46.       return await transactionalEntityManager.delete<TestEntity>(TestEntity, id)
  47.     })
  48.     if (!affected) return ResultData.fail(AppHttpCode.SERVICE_ERROR, '删除部门失败,请稍后尝试')
  49.     return ResultData.ok()
  50.   }
  51.   /** 查询岗位 */
  52.   async findList(dto: FindTestListDto): Promise<ResultData> {
  53.     const { size, page, name, code, status } = dto
  54.     const where = {
  55.       ...(!!name ? { name: Like(`%${name}%`) } : null),
  56.       ...(!!code ? { code: Like(`%${code}%`) } : null),
  57.       ...(![null, undefined].includes(status) ? { status } : null),
  58.     }
  59.     const posts = await this.postRepo.findAndCount({
  60.       where,
  61.       order: { orderNum: 'DESC', id: 'DESC', createDate: 'DESC' },
  62.       skip: size * (page - 1),
  63.       take: size,
  64.     })
  65.     return ResultData.ok({ list: posts[0], total: posts[1] })
  66.   }
  67.   /** 查询单个岗位信息 */
  68.   async findOne(id: string): Promise<ResultData> {
  69.     const post = await this.postRepo.findOne({ where: { id } })
  70.     return ResultData.ok(post)
  71.   }
  72. }
复制代码
  1. // test.controller.ts
  2. import { Controller, Post, Body, Delete, Get, Put, Param, Query } from '@nestjs/common'
  3. import { ApiOperation, ApiTags, ApiBearerAuth } from '@nestjs/swagger'
  4. import { ApiResult } from '../../common/decorators/api-result.decorator'
  5. import { ResultData } from '../../common/utils/result'
  6. import { TestEntity } from './entities/test.entity'
  7. import { TestService } from './test.service'
  8. import { FindTestListDto } from './dto/findTestList.dto'
  9. import { CreateTestDto } from './dto/create-test.dto'
  10. import { UpdateTestDto } from './dto/update-test.dto'
  11. @ApiTags('岗位模块')
  12. @ApiBearerAuth()
  13. @Controller('test')
  14. export class TestController {
  15.   constructor(private readonly testService: TestService) {}
  16.   @Post()
  17.   @ApiOperation({ summary: '创建岗位' })
  18.   @ApiResult(TestEntity)
  19.   async create(@Body() dto: CreateTestDto): Promise<ResultData> {
  20.     return this.testService.create(dto)
  21.   }
  22.   @Put()
  23.   @ApiOperation({ summary: '岗位更新' })
  24.   @ApiResult()
  25.   async update(@Body() dto: UpdateTestDto): Promise<ResultData> {
  26.     return this.testService.update(dto)
  27.   }
  28.   @Get('list')
  29.   @ApiOperation({ summary: '查询岗位列表' })
  30.   @ApiResult(TestEntity, true)
  31.   async find(@Query() dto: FindTestListDto): Promise<ResultData> {
  32.     return this.testService.findList(dto)
  33.   }
  34.   @Get(':id')
  35.   @ApiOperation({ summary: '查询岗位详情' })
  36.   @ApiResult(TestEntity)
  37.   async findOne(@Param('id') id: string): Promise<ResultData> {
  38.     return this.testService.findOne(id)
  39.   }
  40.   @Delete(':id')
  41.   @ApiOperation({ summary: '删除岗位' })
  42.   @ApiResult()
  43.   async delete(@Param('id') id: string): Promise<ResultData> {
  44.     return this.testService.delete(id)
  45.   }
  46. }
复制代码
  1. // test.module.ts
  2. import { Module } from '@nestjs/common'
  3. import { TypeOrmModule } from '@nestjs/typeorm'
  4. import { TestEntity } from './entities/test.entity'
  5. import { TestService } from './test.service'
  6. import { TestController } from './test.controller'
  7. @Module({
  8.   imports: [TypeOrmModule.forFeature([TestEntity])],
  9.   providers: [TestService],
  10.   controllers: [TestController]
  11. })
  12. export class TestModule {}
复制代码
写在背面的话:

前端学习后端头脑绝非易事,一定要实事求是,不可心浮气躁。
背面想再出一个更细的nestjs模块解释,欢迎关注。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表