NestJs服务搭建过程记录,菜鸟笔记。
一、创建项目
$ npm i -g @nestjs/cli
$ nest new project-name
$ cd project-name
$ yarn run start:dev
nest -h 可以查看创建项目的一些快捷指令
二、添加swagger支持
$ yarn add @nestjs/swagger swagger-ui-express
修改main.ts
// main.ts
import { NestFactory } from "@nestjs/core";
//swagger
import { SwaggerModule, DocumentBuilder } from "@nestjs/swagger";
import { AppModule } from "./app.module";
const listenPort = 3000;
async function bootstrap() {
const app = await NestFactory.create(AppModule);
console.log(`listen in location: ${listenPort}`);
//swagger config
const config = new DocumentBuilder()
.setTitle("Cats example")
.setDescription("The cats API description")
.setVersion("1.0")
.addTag("cats")
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("swagger", app, document);
await app.listen(3000);
}
bootstrap();
使用示例: app.controller.ts文件
//app.controller.ts
@Controller()
@ApiTags("APP总模块")
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
@ApiOperation({
summary: "测试接口",
})
getHello(): string {
return this.appService.getGoodBay();
}
}
效果: 打开链接 http://localhost:3000/swagger
三、连接MongoDB数据库
1.安装依赖包
$ yarn add @nestjs/mongoose mongoose
2.创建数据库模块
$ nest g mo db
// DbModule 会被自动加入app.module.ts中
3.连接数据库
在生成的db/db.module.ts 文件中,填入数据库连接。
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
@Module({
imports: [
MongooseModule.forRoot(
"mongodb://user:password@xxx.xxx.xxx:27017/dbname"
),
],
})
export class DbModule {}
- 创建示例
创建User模块
$ nest g interface user
$ nest g mo user
$ nest g service user
$ nest g co user
根据自己习惯对文件进行分层
各个文件代码
user.interface.ts
import { Prop, Schema } from "@nestjs/mongoose";
import { Document } from "mongoose";
import { ApiProperty } from "@nestjs/swagger";
@Schema()
export class User extends Document {
@Prop()
@ApiProperty({
description: "用户名",
example: "admin",
})
readonly username: string;
@Prop()
@ApiProperty({
description: "密码",
example: "123456",
})
readonly password: string;
@Prop()
@ApiProperty({
description: "手机号",
example: "18100000000",
})
readonly phone: string;
}
user.schema.ts
import { SchemaFactory } from "@nestjs/mongoose";
import { User } from "src/interfaces/user.interface";
export const UserSchema = SchemaFactory.createForClass(User);
修改db.module.ts
import { Global, Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { UserSchema } from "./schema/user.schema";
const MONGO_MODELS = MongooseModule.forFeature([
{
name: "USER_MODEL",
schema: UserSchema,
collection: "user",
},
]);
@Global()
@Module({
imports: [
MongooseModule.forRoot(
"mongodb://user:password@xxx.xxx.xxx:27017/dbname"
),
MONGO_MODELS,
],
exports: [MONGO_MODELS],
})
export class DbModule {}
user.service.ts
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { User } from "src/interfaces/user.interface";
@Injectable()
export class UserService {
constructor(
@InjectModel("USER_MODEL") private readonly userModel: Model<User>
) {}
/**
* @description: 注册方法
* @param {User} user
* @return {*}
*/
public async register(user: User) {
return this.userModel
.findOne({
phone: user.phone,
})
.then((res) => {
if (res) {
console.log("该用户已注册");
throw Error("该用户已注册");
}
})
.then(() => {
try {
const createUser = new this.userModel(user);
return createUser.save();
} catch (error) {
throw Error("保存用户失败" + error);
}
})
.catch((err) => {
console.warn(`发生问题--${err}`);
});
}
}
user.controller.ts
import { Controller, Post, Body } from "@nestjs/common";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { User } from "src/interfaces/user.interface";
import { UserService } from "./user.service";
@Controller("user")
@ApiTags("用户模块")
export class UserController {
constructor(private userService: UserService) {}
@Post("register")
@ApiOperation({
summary: "用户注册",
})
async registerUser(@Body() userDto: User) {
return await this.userService.register(userDto);
}
}
打开swagger文档运行:
数据库详情
@干饭,未完待续