1、安装nest脚手架,和初始化项目
npm i -g @nestjs/cli
nest new project-name
2、安装swagger
npm install --save @nestjs/swagger swagger-ui-express
2.1、main.ts,bootstrap函数内
// swagger配置
const options = new DocumentBuilder()
.setTitle('nestjs博客api')
.setDescription('nestjs博客')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api-docs', app, document);
2.2、常用配置参数
// 定义接口组,controller中
@ApiTags('帖子')
// 定义单个接口,controller中
@ApiOperation({ summary: '帖子列表' })
// 定义swagger参数名称,model中
@ApiProperty({description: '帖子标题',example: '测试帖子标题',})
3、使用pipe进行参数校验
npm i --save class-validator class-transformer
3.1、main.ts中开启管道校验
import { ValidationPipe } from '@nestjs/common';
// 开起校验管道,bootstrap中
app.useGlobalPipes(new ValidationPipe());
3.2、对应的model中进行参数校验,例如:post.model.ts
import { IsNotEmpty } from 'class-validator';
// 参数校验
@IsNotEmpty({ message: '标题不能为空' })
4、使用mongodb,包含上面内容完整的代码
npm i @typegoose/typegoose nestjs-typegoose mongoose -S
4.1、连接mongodb数据库,app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PostsModule } from './posts/posts.module';
import { TypegooseModule } from 'nestjs-typegoose';
@Module({
imports: [
// 连接mongodb
TypegooseModule.forRoot('mongodb://localhost:27017/nest-blog-api', {
// useNewUrlParser: true,
}),
PostsModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
4.2、创建模型,post.model.ts
import { ApiProperty } from '@nestjs/swagger';
import { prop } from '@typegoose/typegoose';
import { IsNotEmpty } from 'class-validator';
// 数据库模型
export class Post {
// swagger的参数名称
@ApiProperty({
description: '帖子标题',
example: '测试帖子标题',
})
// 参数校验
@IsNotEmpty({ message: '标题不能为空' })
@prop()
title?: string;
@ApiProperty({
description: '帖子详情',
example: '测试帖子内容',
})
@prop()
content?: string;
@prop()
createTime?: string;
@ApiProperty({
description: '创建人',
example: '创建人11',
required: false,
})
@prop()
createBy?: string;
@prop()
updateTime?: string;
@ApiProperty({
description: '更新人',
example: '更新人11',
required: false,
})
@prop()
updateBy?: string;
@ApiProperty({
description: '数据状态:false:未删除,true:已删除',
example: false,
required: false,
})
@prop()
del_flag?: boolean;
}
// 搜索条件模型
export class SearchDto {
@ApiProperty({ description: '第几页', example: 1 })
pageIndex: number;
@ApiProperty({ description: '一页多少条', example: 10 })
pageSize: number;
@ApiProperty({
description: '帖子详情',
required: false,
})
title: string;
@ApiProperty({
description: '帖子详情',
required: false,
})
content: string;
}
4.3、module中注册模型,posts.module.ts
import { Module } from '@nestjs/common';
import { TypegooseModule } from 'nestjs-typegoose';
import { Post } from './post.model';
import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';
@Module({
// 1.模块中注册数据库模型
imports: [TypegooseModule.forFeature([Post])],
controllers: [PostsController],
providers: [PostsService],
})
export class PostsModule {}
4.4、service中使用模型,基础的crud,posts.service.ts
import { Injectable } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose';
import { Post as PostSchema } from './post.model';
import { getNowTime } from '../utils/dateTime';
@Injectable()
export class PostsService {
constructor(
// 2.引入model,使用模型
@InjectModel(PostSchema)
private readonly postModel: ReturnModelType<typeof PostSchema>,
) {}
// 分页查询
async getPageList(data) {
// MongoDB模型方法
const { pageIndex, pageSize, title, content } = data;
// 组装模糊搜索条件
const search = {
del_flag: false,
title: new RegExp(title),
content: new RegExp(content),
};
// 获取总数
const total = await this.postModel.find(search).count();
// 分页数据
const result = await this.postModel
.find(search)
.skip((pageIndex - 1) * pageSize) //跳过的条数
.limit(pageSize); //查询几条
return {
pageIndex,
pageSize,
total,
result,
};
}
// 新增
async add(data: PostSchema) {
data.createTime = getNowTime();
data.updateTime = getNowTime();
await this.postModel.create(data);
return {
success: true,
};
}
// 详情
async detail(id) {
return await this.postModel.findById(id);
}
// 修改
async update(id, data: PostSchema) {
data.updateTime = getNowTime();
await this.postModel.findByIdAndUpdate(id, data);
return {
success: true,
};
}
// 删除
async remove(id) {
// 物理删除
// await this.postModel.findByIdAndDelete(id);
// 逻辑删除
const updatePostDto: PostSchema = {
updateTime: getNowTime(),
del_flag: true,
};
await this.postModel.findByIdAndUpdate(id, updatePostDto);
return {
success: true,
};
}
}
4.5、controller中使用service,基础的crud,posts.controller.ts
import {
Body,
Controller,
Delete,
Get,
Param,
Post,
Put,
Query,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Post as PostSchema, SearchDto } from './post.model';
import { PostsService } from './posts.service';
@Controller('posts')
// swagger接口分组
@ApiTags('帖子')
export class PostsController {
// 引入service
constructor(private readonly postsService: PostsService) {}
@Get()
// swagger的接口信息定义
@ApiOperation({ summary: '帖子列表' })
index(@Query() searchDto: SearchDto) {
return this.postsService.getPageList(searchDto);
}
@Post()
@ApiOperation({ summary: '创建帖子' })
// 修饰器是修饰变量,不能单独存在
async create(@Body() createPostDto: PostSchema) {
return this.postsService.add(createPostDto);
}
@Get(':id')
@ApiOperation({ summary: '帖子详情' })
async detail(@Param('id') id: string) {
return this.postsService.detail(id);
}
@Put(':id')
@ApiOperation({ summary: '编辑帖子' })
async update(@Param('id') id: string, @Body() updatePostDto: PostSchema) {
return this.postsService.update(id, updatePostDto);
}
@Delete(':id')
@ApiOperation({ summary: '删除帖子' })
async remove(@Param('id') id: string) {
return this.postsService.remove(id);
}
}
网友评论