安装nestjs
官方文档
npm i -g @nestjs/cli
新建项目
nest new nest-blog-api
Which package manager would you ❤️ to use? npm
修改运行端口
//main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(5000);
// 运行端口
}
运行项目
//修改项目后自动重启
npm run start:dev
//或
npm run start
访问localhost:5000
查看nest命令
nest -h
生成模块
nest g mo posts
生成路由
nest g co posts
生成服务
nest g s posts
修改posts.module.ts
@Module({
imports: [TypegooseModule.forFeature([Post])],
controllers: [PostsController]
})
export class PostsModule {}
根据代码生成文档swagger
安装
npm install --save @nestjs/swagger swagger-ui-express
修改main.js
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
...
const options = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
连接数据库
npm i -s @typegoose/typegoose
npm i -s mongoose
npm i -s @types/mongoose
开启全局验证
npm i --save class-validator class-transformer
//main.ts
app.useGlobalPipes(new ValidationPipe())
使用
@IsNotEmpty({message:'请填写标题'})
使用typegoose减少耦合
npm install --save nestjs-typegoose
修改app.module.ts
@Module({
imports: [
TypegooseModule.forRoot("mongodb://localhost:27017/nest-blog-api", {
useNewUrlParser: true
}),
PostsModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
修改posts.module.ts
@Module({
imports: [TypegooseModule.forFeature([Post])],
controllers: [PostsController]
})
自动在模型字段加上创建和更新时间
@modelOptions({
schemaOptions:{
timestamps:true,
}
})
export class User {
@ApiProperty({ example: '张三', description: '用户名' })
@prop()
username: string
@ApiProperty({ example: '1234', description: '密码' })
@prop()
password: string
}
外键关联
model.ts
@arrayProp({ itemsRef:'Episode'})
episodes:Ref<Episode>[]
注册插件
@Module({
imports: [MongooseModule.forFeatureAsync([
{
name: 'Post',
useFactory: () => {
const schema = PostSchema;
schema.plugin(require('mongoose-paginate-v2'));
return schema;
}
}
])
],
controllers: [PostsController]
})
export class PostsModule { }
分页
@Get()
@ApiOperation({ summary: '显示博客列表' })
async index(@Query('page') page: string = '1', @Query('limit') limit: string = '5') {
let page_num = parseInt(page)
let limit_num = parseInt(limit)
let total = await this.postModel.count({})
let data = await this.postModel.find({}, null, { skip: (page_num - 1) * limit_num, limit: limit_num })
return { total: total, data: data }
}
注意不加await将导致Converting circular structure to JSON错误
npm i --save @nestjs/config