马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
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模块解释,欢迎关注。
|